Skip to content

Commit

Permalink
fix: don't cache rejected promises (#1238)
Browse files Browse the repository at this point in the history
Co-authored-by: Valentin Vetter <[email protected]>
  • Loading branch information
BeLi4L and Valentin Vetter authored Dec 31, 2024
1 parent a29d46b commit 161459d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/forestadmin-client/src/utils/ttl-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
export default class TTLCache<V> {
private readonly stateMap = new Map<
string,
{ promise: Promise<V | undefined> | V | undefined; expirationTimestamp: number }
{ promise: Promise<V | undefined>; expirationTimestamp: number }
>();

constructor(
private readonly fetchMethod: (key: string) => Promise<V | undefined> | V | undefined,
private readonly fetchMethod: (key: string) => Promise<V | undefined>,
private readonly ttl = 1000,
) {}

Expand All @@ -24,6 +24,11 @@ export default class TTLCache<V> {
const fetch = this.fetchMethod(key);
this.stateMap.set(key, { promise: fetch, expirationTimestamp: now + this.ttl });

fetch.catch(() => {
// Don't cache rejected promises
this.stateMap.delete(key);
});

return fetch;
}

Expand Down
16 changes: 16 additions & 0 deletions packages/forestadmin-client/test/utils/ttl-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ describe('TTL Cache', () => {

expect(fetchMethod).toHaveBeenCalledTimes(2);
});

it('should not cache a rejected promise', async () => {
const fetchMethod = jest
.fn()
.mockRejectedValueOnce(new Error('first'))
.mockResolvedValueOnce('second');

const cache = new TTLCache<string>(fetchMethod);

await expect(() => cache.fetch('key')).rejects.toThrow('first');

const fetch2 = await cache.fetch('key');
expect(fetch2).toEqual('second');

expect(fetchMethod).toHaveBeenCalledTimes(2);
});
});

describe('clear', () => {
Expand Down

0 comments on commit 161459d

Please sign in to comment.