Socialify

Folder ..

Viewing cache.ts
34 lines (26 loc) • 981.0 B

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Redis } from 'ioredis';
/* eslint-disable import/no-anonymous-default-export */

/*
TLDR; " Expires " is seconds based. for example 60*60 would = 3600 (an hour)
*/

const fetch = async <T>(redis: Redis, key: string, fetcher: () => T, expires: number) => {
  const existing = await get<T>(redis, key);
  if (existing !== null) return existing;

  return set(redis, key, fetcher, expires);
};

const get = async <T>(redis: Redis, key: string): Promise<T> => {
  console.log('GET: ' + key);
  const value = await redis.get(key);
  if (value === null) return null as any;

  return JSON.parse(value);
};

const set = async <T>(redis: Redis, key: string, fetcher: () => T, expires: number) => {
  console.log(`SET: ${key}, EXP: ${expires}`);
  const value = await fetcher();
  await redis.set(key, JSON.stringify(value), 'EX', expires);
  return value;
};

const del = async (redis: Redis, key: string) => {
  await redis.del(key);
};

export default { fetch, set, get, del };