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

feat. add has method #7

Merged
merged 6 commits into from
Jun 19, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:

strategy:
matrix:
node-version: [12.x, 14.x, 15.x]
node-version: [12.x, 14.x, 16.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
env:
MYSQL_DB_DATABASE: keyv_test
Expand Down
16 changes: 16 additions & 0 deletions packages/keyv-test-suite/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,22 @@ const keyvApiTests = (test, Keyv, store) => {
t.is(await keyv.get('fizz'), undefined);
});

test.serial('.has(key) returns a Promise', t => {
const keyv = new Keyv({ store: store() });
t.true(keyv.has('foo') instanceof Promise);
});

test.serial('.has(key) resolves to true', async t => {
const keyv = new Keyv({ store: store() });
await keyv.set('foo', 'bar');
t.is(await keyv.has('foo'), true);
});

test.serial('.has(key) with nonexistent key resolves to false', async t => {
const keyv = new Keyv({ store: store() });
t.is(await keyv.has('foo'), false);
});

test.after.always(async () => {
const keyv = new Keyv({ store: store() });
await keyv.clear();
Expand Down
19 changes: 14 additions & 5 deletions packages/keyv/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ class Keyv extends EventEmitter {
options
);

this.store = this.options.store;

if (!this.store) {
this.store = new Map();
}
this.store = this.options.store || new Map();

this.store.namespace = this.options.namespace;

Expand Down Expand Up @@ -83,6 +79,19 @@ class Keyv extends EventEmitter {
});
}

has(key) {
const keyPrefixed = this._getKeyPrefix(key);
const store = this.store;
if (typeof store.has === 'function') {
return Promise.resolve()
.then(() => store.has(keyPrefixed));
}

return Promise.resolve()
.then(() => store.get(keyPrefixed))
.then(data => data !== undefined);
}

set(key, value, ttl) {
const keyPrefixed = this._getKeyPrefix(key);
if (typeof ttl === 'undefined') {
Expand Down