diff --git a/lib/index.js b/lib/index.js index 95609a6..fe933d9 100644 --- a/lib/index.js +++ b/lib/index.js @@ -60,6 +60,30 @@ function Config(parent, defaultEnvVar, customizer) { return settings.hasOwnProperty(setting) || (!!parent && parent.has(setting)); }; + config.snapshot = function () { + var snapshot = [{}, {}]; + Object.keys(settings).forEach(function (key) { + snapshot[0][key] = settings[key]; + }); + + Object.keys(environments).forEach(function (key) { + snapshot[1][key] = environments[key].snapshot(); + }); + + return snapshot; + }; + + config.restore = function (snapshot) { + var self = this; + settings = snapshot[0]; + + environments = {}; + Object.keys(snapshot[1]).forEach(function (key) { + environments[key] = new Config(self, defaultEnvVar, customizer); + environments[key].restore(snapshot[1][key]); + }); + }; + Object.defineProperties(config, { default: { get: function () { diff --git a/test/config-test.js b/test/config-test.js index 9b73838..e700528 100644 --- a/test/config-test.js +++ b/test/config-test.js @@ -280,3 +280,49 @@ describe('Config customization', function () { spy.callCount.should.equal(2); }); }); + +describe('Snapshot and restore', function () { + it('should save and restore configuration state', function () { + var c = envconf.createConfig(); + c.configure(function () { + c.set('first', 'one'); + c.set('second', 'two'); + }); + + var ss = c.snapshot(); + c.set('first', 'changed'); + c.set('added', 'new value'); + + c.restore(ss); + + c.get('first').should.equal('one'); + c.get('second').should.equal('two'); + should.not.exist(c.get('added')); + }); + + it('should save and restore child environments', function () { + var c = envconf.createConfig(); + c.configure('dev', function (dev) { + dev.set('devFirst', 'one'); + dev.configure('devsub', function (devsub) { + devsub.set('subsubFirst', 'a sub sub value'); + }); + }); + + c.configure('prod', function (prod) { + prod.set('prodvalue', 'a value'); + }); + + var snapshot = c.snapshot(); + + c('dev').set('devFirst', 'changed value'); + c('prod').configure('addedEnvironment', function (added) { + added.set('newEnvValue', 1234); + }); + + c.restore(snapshot); + + c('dev').get('devFirst').should.equal('one'); + c('prod').environments.should.not.include('addedEnvironment'); + }); +});