Last active
July 31, 2021 16:20
-
-
Save sibelius/f41020d0a8aa07b033c37f9f3de5065a to your computer and use it in GitHub Desktop.
Basic RedisCache implementation
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, { KeyType, Ok } from 'ioredis'; | |
const redis = new Redis(process.env.REDIS_HOST); | |
export const set = async ( | |
key: KeyType, | |
seconds: number, | |
value: Record<string, unknown>, | |
): Promise<Ok> => | |
// https://redis.io/commands/psetex | |
// Set key to hold the string value and set key to timeout | |
redis.setex(key, seconds, JSON.stringify(value)); | |
export const get = async <T extends Record<string, unknown>>( | |
key: KeyType, | |
): Promise<T | null> => { | |
const value = await redis.get(key); | |
if (!value) { | |
return value; | |
} | |
try { | |
return JSON.parse(value); | |
} catch (err) { | |
return value; | |
} | |
}; |
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 * as RedisCache from './RedisCache'; | |
const fetchWithCache = (url, options, cacheKey, ttl) => { | |
const cached = await RedisCache.get(cacheKey); | |
if (cached) { return cached; } | |
const response = await fetch(url, options); | |
if (response.ok) { | |
const data = await response.json(); | |
if (data) { | |
// save to redis cache | |
await RedisCache.set(cacheKey, ttl, data); | |
} | |
} | |
const text = await response.text(); | |
return text; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment