Skip to content

Commit

Permalink
fix: do not accidentally cache ttl: 0 entries forever
Browse files Browse the repository at this point in the history
  • Loading branch information
Xiphe committed Jul 28, 2022
1 parent 7e737ef commit 7261b35
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
28 changes: 27 additions & 1 deletion src/cachified.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,32 @@ describe('cachified', () => {
`);
});

it('immediately refreshes when ttl is 0', async () => {
const cache = new Map<string, CacheEntry<string>>();

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

currentTime = 1;
const value2 = await cachified({
cache,
key: 'test',
ttl: 0,
getFreshValue() {
return 'TWO';
},
});

expect(value).toBe('ONE');
expect(value2).toBe('TWO');
});

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 Expand Up @@ -960,7 +986,7 @@ describe('cachified', () => {
await getValue(() => (event) => {
if (event.name === 'getCachedValueError') {
expect(event.error).toMatchInlineSnapshot(
`[Error: Cache entry for test does not have a value property]`,
`[Error: Cache entry for for test does not have a value property]`,
);
}
}),
Expand Down
4 changes: 2 additions & 2 deletions src/shouldRefresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import type { CacheMetadata } from './common';
export function shouldRefresh(
metadata: CacheMetadata,
): 'now' | 'stale' | false {
if (metadata.ttl) {
const valid = metadata.createdTime + metadata.ttl;
if (metadata.ttl !== null) {
const valid = metadata.createdTime + (metadata.ttl || 0);
const stale = valid + (metadata.swv || 0);
const now = Date.now();
if (now <= valid) {
Expand Down

0 comments on commit 7261b35

Please sign in to comment.