Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for req.hostname #224

Merged
merged 1 commit into from
Sep 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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