Skip to content

Instantly share code, notes, and snippets.

@alii
Last active September 26, 2023 23:07
Show Gist options
  • Save alii/30ac66ef07e62086ed7144d534b4768b to your computer and use it in GitHub Desktop.
Save alii/30ac66ef07e62086ed7144d534b4768b to your computer and use it in GitHub Desktop.
wrap-redis.ts
async function wrapRedis<T>(key: string, fn: () => Promise<T>, seconds = 60): Promise<T> {
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const recent = await fn();
if (recent) {
await redis.set(key, JSON.stringify(recent), 'ex', seconds);
}
return recent;
}
// Usage
app.get('/users/:id', async (req, res) => {
const user = await wrapRedis(`user:${req.params.id}`, () => {
return prisma.user.findFirst({
where: {id: req.params.id},
});
});
const {password, ...rest} = user;
res.json(rest);
});
@Looskie
Copy link

Looskie commented Mar 7, 2021

lol thanks for the code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment