Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active July 31, 2021 16:20
Show Gist options
  • Save sibelius/f41020d0a8aa07b033c37f9f3de5065a to your computer and use it in GitHub Desktop.
Save sibelius/f41020d0a8aa07b033c37f9f3de5065a to your computer and use it in GitHub Desktop.
Basic RedisCache implementation
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;
}
};
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