Skip to content

Commit

Permalink
Add merge support to Storage.
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima committed Feb 15, 2021
1 parent f4336d9 commit 52c90a2
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 5 deletions.
17 changes: 14 additions & 3 deletions lib/util/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,20 @@ class Storage {
_.isObject(defaults),
'Storage `defaults` method only accept objects'
);
const value = _.defaults(this.getAll(), defaults);
this.set(value);
return value;
const store = _.defaults({}, this._store, defaults);
this._persist(store);
return this.getAll();
}

/**
* @param {Object} defaults Key-value object to store.
* @return {*} val Returns the merged object.
*/
merge(source) {
assert(_.isObject(source), 'Storage `merge` method only accept objects');
const value = _.merge({}, this._store, source);
this._persist(value);
return this.getAll();
}

/**
Expand Down
53 changes: 51 additions & 2 deletions test/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,55 @@ describe('Storage', () => {
});
});

describe('#merge()', () => {
beforeEach(function () {
this.store.set('val1', 1);
});

it('should merge values if not predefined', function () {
this.store.merge({val1: 3, val2: 4});

assert.strictEqual(this.store.get('val1'), 3);
assert.strictEqual(this.store.get('val2'), 4);
});

it('should require an Object as argument', function () {
assert.throws(this.store.defaults.bind(this.store, 'foo'));
});

describe('@return', () => {
beforeEach(function () {
this.storePath = path.join(tmpdir, 'defaultreturn.json');
this.store = new Storage('test', this.fs, this.storePath);
this.store.set('val1', 1);
this.store.set('foo', 'bar');
});

afterEach(function () {
rm(this.storePath);
});

it('should return the original object', function () {
assert.deepStrictEqual(this.store.merge({}), {foo: 'bar', val1: 1});
});

it('should return an object with replaced values', function () {
assert.deepStrictEqual(this.store.merge({foo: 'baz'}), {
foo: 'baz',
val1: 1
});
});

it('should return an object with new values', function () {
assert.deepStrictEqual(this.store.merge({food: 'pizza'}), {
foo: 'bar',
val1: 1,
food: 'pizza'
});
});
});
});

it('stores sharing the same store file with and without namespace', function () {
const store = new Storage(this.fs, this.storePath);
store.set('test', {bar: 'foo'});
Expand Down Expand Up @@ -352,11 +401,11 @@ describe('Storage', () => {
this.store.get('foo');
});

it('loads', function () {
it('should load', function () {
assert(this.store._cachedStore);
});

it("doesn't loads when disabled", function () {
it('should not load when disabled', function () {
const store = new Storage('test', this.fs, this.storePath, {
disableCache: true
});
Expand Down

0 comments on commit 52c90a2

Please sign in to comment.