From 7e33e1d0e800acb6c2a37f9f376580833ae2db53 Mon Sep 17 00:00:00 2001 From: Ricky Boyce Date: Fri, 16 Feb 2018 16:36:05 +1300 Subject: [PATCH] Added app.extend() Added app.extend(), which provides an easy way to update certain properties of a setting. --- lib/application.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ test/config.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/lib/application.js b/lib/application.js index 91f77d241e..80a65eab3d 100644 --- a/lib/application.js +++ b/lib/application.js @@ -383,6 +383,50 @@ app.set = function set(setting, val) { return this; }; +/** + * Extend `setting` with `val`, or return `setting`'s value. + * + * app.set('foo', { 'bar' : 1 }) + * app.expand('foo', { 'baz' : 1 }); + * app.expand('foo'); + * // => { "bar" : 1, "baz" : 1 } + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.extend = function(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + if (typeof val === 'undefined') { + return this; + } else if (val === null || typeof val !== 'object') { + throw new Error('value needs to be an object'); + } + + debug('extend "%s" with %o', setting, val); + + var currentSetting = this.settings[setting]; + + // no object yet, set value + if (currentSetting === null || typeof currentSetting !== 'object') { + this.settings[setting] = val; + return this; + } + + // extend value + this.settings[setting] = Object.assign(this.settings[setting], val); + + return this; +}; + /** * Return the app's absolute pathname * based on the parent(s) that have diff --git a/test/config.js b/test/config.js index 17a02b7eba..cfc99e670c 100644 --- a/test/config.js +++ b/test/config.js @@ -118,6 +118,38 @@ describe('config', function () { }) }) + describe('.extend()', function () { + it('should set if value is nonexistent', function () { + var app = express(); + app.extend('foo', { 'bar' : 1 }); + assert.deepEqual(app.get('foo'), { 'bar' : 1 }); + }) + + it('should extend an object', function () { + var app = express(); + app.extend('foo', { 'bar' : 1 }); + app.extend('foo', { 'baz' : 1 }); + assert.deepEqual(app.get('foo'), { 'bar' : 1, 'baz' : 1 }); + }) + + it('should return the app', function () { + var app = express(); + assert.equal(app.extend('foo', { 'bar' : 1 }), app); + }) + + it('should return the app when undefined', function () { + var app = express(); + assert.equal(app.extend('foo', undefined), app); + }) + + it('should thorw on bad value', function () { + var app = express(); + (function(){ + app.extend('foo', null); + }).should.throw('value needs to be an object'); + }) + }) + describe('.enable()', function(){ it('should set the value to true', function(){ var app = express();