1
import { KeyValueCache } from "apollo-server-caching"
2

3 1
const defaultStore = new Map()
4

5
type Cache = <V = any>(
6
  key: string,
7
  value: V,
8
  store?: KeyValueCache<V> | Map<string, V>
9
) => Promise<V | undefined>
10

11 1
export const cache: Cache = async (key, value, store = defaultStore) => {
12 1
  if (store.get(key)) {
13 0
    return store.get(key)
14
  }
15 1
  await store.set(key, typeof value === `function` ? value() : value)
16 0
  return store.get(key)
17
}
18

19 1
export const memoize = <
20
  F extends (...args: any[]) => any,
21
  C extends KeyValueCache<ReturnType<F>>
22
>(
23
  fn: F,
24 1
  store: C | Map<string, ReturnType<F>> = new Map()
25 0
) => (...args: any[]) =>
26 1
  cache<() => ReturnType<F>>(
27
    `${fn.toString()}(${JSON.stringify(args)})`,
28 0
    () => fn(...args),
29
    store
30
  ) || null

Read our documentation on viewing source code .

Loading