Skip to content

Commit

Permalink
fix: only define getter request utility variables once.
Browse files Browse the repository at this point in the history
  • Loading branch information
teclone committed Nov 29, 2018
1 parent dd2208e commit d74b299
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 20 deletions.
39 changes: 19 additions & 20 deletions src/modules/Request.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,28 @@
*@module Request
*/

import Util from './Util';
import {IncomingMessage as Request} from 'http';

Object.defineProperties(Request.prototype, {
/**
*@type {boolean}
*@memberof Request#
*/
isHttps: {
get() {
return this.connection.encrypted;
}
},
const proto = Request.prototype;

/**
*@type {string}
*@memberof Request#
*/
hostname: {
get() {
const host = this.headers['host'];
return typeof host === 'string'? host.replace(/:\d+$/, '') : '';
}
}
/**
*@type {boolean}
*@name isHttps
*@memberof Request#
*/
Util.defineGetter(proto, 'isHttps', function() {
return this.connection.encrypted;
});

/**
*@type {string}
*@name hostname
*@memberof Request#
*/
Util.defineGetter(proto, 'hostname', function() {
const host = this.headers['host'];
return typeof host === 'string'? host.replace(/:\d+$/, '') : '';
});

export default Request;
14 changes: 14 additions & 0 deletions src/modules/Util.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,4 +288,18 @@ export default {
}
return defaultValue;
},

/**
* defines a getter property on the target object if it is not yet defined
*@param {Object} target - the target object
*@param {string} name - property name
*@param {Function} getter - the getter function
*@return {this}
*/
defineGetter(target, name, getter) {
if (typeof target[name] === 'undefined')
Object.defineProperty(target, name, {get: getter});

return this;
}
};
32 changes: 32 additions & 0 deletions test/unit/modules/Util.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,4 +289,36 @@ describe('Util module', function() {
expect(Util.value('height', null, '5ft')).to.equal('5ft');
});
});

describe('.defineGetter(target, name, getter)', function() {
it(`should define the given getter function on the target object for the given
property key name if it does not exist`, function() {
const target = {
_name: 'Johnson'
};

Util.defineGetter(target, 'name', function() {
return this._name;
});

expect(target.name).to.equals('Johnson');
});

it(`should do nothing if given property key name already exists`, function() {
const target = {
_name: 'Johnson',
_age: '28yrs'
};

Util.defineGetter(target, 'name', function() {
return this._name;
});

Util.defineGetter(target, 'name', function() {
return this._age;
});

expect(target.name).to.equals('Johnson');
});
});
});

0 comments on commit d74b299

Please sign in to comment.