Skip to content

Commit

Permalink
Merge pull request #7 from keyvhq/feature-has
Browse files Browse the repository at this point in the history
feat. add `has` method
  • Loading branch information
Kikobeats committed Jun 19, 2021
2 parents c204f58 + 78d448a commit d887e36
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
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
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
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

0 comments on commit d887e36

Please sign in to comment.