Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Created August 6, 2021 23:18
Show Gist options
  • Save gaurangrshah/aeb3e3b64a067519a5113a4de96a6dd4 to your computer and use it in GitHub Desktop.
Save gaurangrshah/aeb3e3b64a067519a5113a4de96a6dd4 to your computer and use it in GitHub Desktop.
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