Skip to content

Commit

Permalink
Allow cache.set(x, undefined) to delete the cached item (#26)
Browse files Browse the repository at this point in the history
Co-authored-by: Federico <me@fregante.com>
  • Loading branch information
cheap-glitch and fregante authored Nov 22, 2020
1 parent fbc260a commit c7a1e23
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
23 changes: 13 additions & 10 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,18 +68,21 @@ async function get<TValue extends Value>(key: string): Promise<TValue | undefine
}

async function set<TValue extends Value>(key: string, value: TValue, maxAge: TimeDescriptor = {days: 30}): Promise<TValue> {
if (typeof value === 'undefined') {
// @ts-expect-error This never happens in TS because `value` can't be undefined
return;
if (arguments.length < 2) {
throw new TypeError('Expected a value as the second argument');
}

const internalKey = `cache:${key}`;
await storageSet({
[internalKey]: {
data: value,
maxAge: timeInTheFuture(maxAge)
}
});
if (typeof value === 'undefined') {
await delete_(key);
} else {
const internalKey = `cache:${key}`;
await storageSet({
[internalKey]: {
data: value,
maxAge: timeInTheFuture(maxAge)
}
});
}

return value;
}
Expand Down
11 changes: 8 additions & 3 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,15 @@ test.serial('has() with expired cache', async t => {
t.is(await cache.has('name'), false);
});

test.serial('set() without a value', async t => {
await t.throwsAsync(cache.set('name'), {instanceOf: TypeError, message: 'Expected a value as the second argument'});
});

test.serial('set() with undefined', async t => {
await cache.set('name');
// StorageArea.set should not be called with `undefined`
t.is(chrome.storage.local.set.callCount, 0);
await cache.set('name', 'Anne');
await cache.set('name', undefined);
// Cached value should be erased
t.is(await cache.has('name'), false);
});

test.serial('set() with value', async t => {
Expand Down

0 comments on commit c7a1e23

Please sign in to comment.