35 lines
664 B
TypeScript
35 lines
664 B
TypeScript
export const cache = <T>(ttl: number) => {
|
|
type Cache = { promise: Promise<T>, timestamp: number };
|
|
const store = new Map<string, Cache>();
|
|
|
|
const get = async (key: string, fetcher: () => Promise<T>) => {
|
|
if (store.has(key)) {
|
|
const cached = store.get(key)!;
|
|
|
|
if (Date.now() - cached.timestamp < ttl) {
|
|
return cached.promise;
|
|
} else {
|
|
store.delete(key);
|
|
}
|
|
}
|
|
|
|
try {
|
|
const promise = fetcher();
|
|
|
|
store.set(key, {
|
|
promise,
|
|
timestamp: Date.now()
|
|
});
|
|
|
|
return promise;
|
|
} catch (error) {
|
|
store.delete(key);
|
|
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
return {
|
|
get
|
|
};
|
|
}; |