Skip to content

Commit

Permalink
Keyv - adding namespace as a property (#1170)
Browse files Browse the repository at this point in the history
* keyv - adding namespace as a property

* Update README.md

* Update README.md
  • Loading branch information
jaredwray authored Oct 21, 2024
1 parent d20ef5f commit 5489fd5
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/keyv/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,13 @@ The connection string URI.

Merged into the options object as options.uri.

### .namespace

Type: `String`
Default: `'keyv'`

This is the namespace for the current instance. When you set it it will set it also on the storage adapter. This is the preferred way to set the namespace over `.opts.namespace`.

### options

Type: `Object`
Expand Down
19 changes: 19 additions & 0 deletions packages/keyv/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,25 @@ export class Keyv<GenericValue = any> extends EventManager {
}
}

/**
* Get the current namespace.
* @returns {string | undefined} The current namespace.
*/
public get namespace(): string | undefined {
return this.opts.namespace;
}

/**
* Set the current namespace.
* @param {string | undefined} namespace The namespace to set.
*/
public set namespace(namespace: string | undefined) {
this.opts.namespace = namespace;
if (this.opts.store) {
this.opts.store.namespace = namespace;
}
}

generateIterator(iterator: IteratorFunction): IteratorFunction {
const function_: IteratorFunction = async function * (this: any) {
for await (const [key, raw] of (typeof iterator === 'function'
Expand Down
10 changes: 10 additions & 0 deletions packages/keyv/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -649,3 +649,13 @@ test.it('Keyv stats enabled should create counts', async t => {
t.expect(keyv.stats.deletes).toBe(1);
t.expect(keyv.stats.sets).toBe(1);
});

test.it('should be able to set the namespace via property', async t => {
const store = new KeyvSqlite({uri: 'sqlite://test/testdb.sqlite'});
const keyv = new Keyv({store});
t.expect(keyv.namespace).toBe('keyv');
t.expect(store.namespace).toBe('keyv');
keyv.namespace = 'test';
t.expect(keyv.namespace).toBe('test');
t.expect(store.namespace).toBe('test');
});

0 comments on commit 5489fd5

Please sign in to comment.