Skip to content

Commit

Permalink
fix: allow falsy values in cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Xiphe committed Aug 2, 2022
1 parent 7261b35 commit 94c3dcf
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
46 changes: 46 additions & 0 deletions src/cachified.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,52 @@ describe('cachified', () => {
expect(value2).toBe('TWO');
});

it('caches undefined values', async () => {
const cache = new Map<string, CacheEntry<undefined>>();

const value = await cachified({
cache,
key: 'test',
getFreshValue() {
return undefined;
},
});

const value2 = await cachified({
cache,
key: 'test',
getFreshValue() {
throw new Error('🛸');
},
});

expect(value).toBe(undefined);
expect(value2).toBe(undefined);
});

it('caches null values', async () => {
const cache = new Map<string, CacheEntry<null>>();

const value = await cachified({
cache,
key: 'test',
getFreshValue() {
return null;
},
});

const value2 = await cachified({
cache,
key: 'test',
getFreshValue() {
throw new Error('🛸');
},
});

expect(value).toBe(null);
expect(value2).toBe(null);
});

it('throws when no fresh value can be received for empty cache', async () => {
const cache = new Map<string, CacheEntry<string>>();
const reporter = createReporter();
Expand Down
6 changes: 3 additions & 3 deletions src/cachified.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ export async function cachified<Value>(
const hasPendingValue = () => {
return pendingValues.has(key);
};
const cachedValue =
(!forceFresh && (await getCachedValue(context, report, hasPendingValue))) ||
CACHE_EMPTY;
const cachedValue = !forceFresh
? await getCachedValue(context, report, hasPendingValue)
: CACHE_EMPTY;
if (cachedValue !== CACHE_EMPTY) {
return cachedValue;
}
Expand Down

0 comments on commit 94c3dcf

Please sign in to comment.