Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keyv - adding namespace as a property #1170

Merged
merged 3 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
});
Loading