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

Allow cache.set(x, undefined) to delete the cached item #26

Merged
merged 9 commits into from
Nov 22, 2020
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> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the only issue here is that undefined isn't accepted by the types

Suggested change
async function set<TValue extends Value>(key: string, value: TValue, maxAge: TimeDescriptor = {days: 30}): Promise<TValue> {
async function set<TValue extends Value>(key: string, value: TValue | undefined, maxAge: TimeDescriptor = {days: 30}): Promise<TValue> {

I released a prerelease 4.3.0-0 if you want to try it in RGH in the original issue that discussed this

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);
cheap-glitch marked this conversation as resolved.
Show resolved Hide resolved
} 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