batching events
This commit is contained in:
committed by
Carl-Gerhard Lindesvärd
parent
244aa3b0d3
commit
5e225b7ae6
@@ -4,14 +4,25 @@ export function cacheable<T extends (...args: any) => any>(
|
||||
fn: T,
|
||||
expire: number
|
||||
) {
|
||||
return async function (...args: Parameters<T>): Promise<ReturnType<T>> {
|
||||
return async function (
|
||||
...args: Parameters<T>
|
||||
): Promise<Awaited<ReturnType<T>>> {
|
||||
// JSON.stringify here is not bullet proof since ordering of object keys matters etc
|
||||
const key = `cachable:${fn.name}:${JSON.stringify(args)}`;
|
||||
const cached = await redis.get(key);
|
||||
if (cached) {
|
||||
return JSON.parse(cached);
|
||||
try {
|
||||
return JSON.parse(cached);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse cache', e);
|
||||
}
|
||||
}
|
||||
const result = await fn(...(args as any));
|
||||
redis.setex(key, expire, JSON.stringify(result));
|
||||
|
||||
if (result !== undefined || result !== null) {
|
||||
redis.setex(key, expire, JSON.stringify(result));
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user