Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
subins2000 committed Aug 20, 2020
1 parent 22b6ea3 commit 22c1270
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
19 changes: 19 additions & 0 deletions source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,25 @@ class Conf<T extends Record<string, any> = Record<string, unknown>> implements I
this.store = store;
}

/**
Append an item or multiple items to an array
@param {key|object} - You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties. Or a hashmap of items to set at once.
@param value - Must be JSON serializable. Trying to set the type `undefined`, `function`, or `symbol` will result in a `TypeError`.
*/
appendToArray<Key extends keyof T>(key: Key, value: Required<T>[Key]): void;
// This overload is used for dot-notation access.
appendToArray<Key extends string>(key: Key, value: Required<T>[Key]): void {
const list = this.get(key, [] as T[Key]);

if (!Array.isArray(list)) {
throw new TypeError('Config param already set and is not array');
}

list.push(value);
this.set(key, list);
}

/**
Check if an item exists.
Expand Down
11 changes: 11 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,17 @@ test('.set() - invalid key', t => {
}, {message: 'Expected `key` to be of type `string` or `object`, got number'});
});

test('.appendToArray()', t => {
t.context.config.set('foo', [fixture]);
t.context.config.set('baz.boo', [fixture]);
t.context.config.appendToArray('foo', '🐴');
t.context.config.appendToArray('baz.boo', '🐴');
t.context.config.appendToArray('bar', '🐴'); // Will create new item with array
t.deepEqual(t.context.config.get('foo'), [fixture, '🐴']);
t.deepEqual(t.context.config.get('baz.boo'), [fixture, '🐴']);
t.deepEqual(t.context.config.get('bar'), ['🐴']);
});

test('.has()', t => {
t.context.config.set('foo', fixture);
t.context.config.set('baz.boo', fixture);
Expand Down

0 comments on commit 22c1270

Please sign in to comment.