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

fix: don't cache rejected promises #1238

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading