Created
August 6, 2021 23:18
-
-
Save gaurangrshah/aeb3e3b64a067519a5113a4de96a6dd4 to your computer and use it in GitHub Desktop.
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
import { redis } from './redis'; | |
const fetch = async (key, fetcher, expires) => { | |
const existing = await get(key); | |
// If the key is already in redis, return it | |
if (existing !== null) return existing; | |
// Otherwise, set it and return the value | |
else set(key, fetcher, expires); | |
}; | |
const get = async (key) => { | |
const value = await redis.get(key); | |
// If the key is not in redis, return null | |
if (value === null) return null; | |
// Otherwise, return the value | |
return JSON.parse(value); | |
}; | |
const set = async (key, fetcher, expires) => { | |
const value = await fetcher(); | |
// If the value is null, return | |
await redis.set(key, JSON.stringify(value), 'EX', expires); | |
// Otherwise, return the value | |
return value; | |
}; | |
// | |
const del = async (key) => await redis.del(key); | |
export default { fetch, del }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment