Last active
September 26, 2023 23:07
-
-
Save alii/30ac66ef07e62086ed7144d534b4768b to your computer and use it in GitHub Desktop.
wrap-redis.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lol thanks for the code!