Skip to content

Commit

Permalink
feat: add support for req.hostname (#224)
Browse files Browse the repository at this point in the history
  • Loading branch information
storm1ng authored Sep 28, 2020
1 parent 9020c97 commit 74440bc
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/mockRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,24 @@ function createRequest(options) {
this.emit('end');
};

/**
* Function: hostname
*
* Hostname is the main domain of the host without the subdomains and port.
*
*/
mockRequest.hostname = (function() {
if (!mockRequest.headers.host) {
return '';
}

var offset = 2;
var hostname = mockRequest.headers.host.split(':')[0].split('.');
var start = hostname.length - offset;
var end = hostname.length;
return hostname.slice(start, end).join('.');
}());

/**
* Function: subdomains
*
Expand Down
41 changes: 41 additions & 0 deletions test/lib/mockRequest.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,47 @@ describe('mockRequest', function() {

});

describe('.hostname', function() {

it('should return the host\'s main domain', function() {
var options = {
headers: {
host: 'tobi.ferrets.example.com:5000'
}
};
request = mockRequest.createRequest(options);
expect(request.hostname).to.equal('example.com');

options.headers.host = 'tobi.ferrets.example.com';
request = mockRequest.createRequest(options);
expect(request.hostname).to.equal('example.com');

options.headers.host = 'example.com';
request = mockRequest.createRequest(options);
expect(request.hostname).to.equal('example.com');

options.headers.host = 'example.com:8443';
request = mockRequest.createRequest(options);
expect(request.hostname).to.equal('example.com');

options.headers.host = 'localhost:3000';
request = mockRequest.createRequest(options);
expect(request.hostname).to.equal('localhost');

});

it('should return an empty string', function () {
var options = {
headers: {
key1: 'key1'
}
};
request = mockRequest.createRequest(options);
expect(request.hostname).to.equal('');
});

});

describe('.subdomains', function() {

it('should returns the host subdomains', function() {
Expand Down

0 comments on commit 74440bc

Please sign in to comment.