-
Notifications
You must be signed in to change notification settings - Fork 58
/
cache.js
37 lines (29 loc) · 917 Bytes
/
cache.js
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
35
36
37
import pLog from 'proc-log'
import timers from 'timers/promises'
// A memory cache for expensive requests like check-runs
// which can get called for the same commit multiple times
// in workspaces. Also used if we retry the whole thing
// again during the same process
const CACHE = new Map()
const cacheKey = (args) => args
.filter(a => a != null)
.map((a) => JSON.stringify(a))
.join('__')
const cacheMethod = (fn, { delay } = {}) => {
if (!CACHE.has(fn)) {
CACHE.set(fn, new Map())
}
return async (...args) => {
const key = cacheKey(args)
if (CACHE.get(fn).has(key)) {
pLog.log.info('cache', 'returning', fn.name, key)
return CACHE.get(fn).get(key)
}
const res = await fn(...args)
// only use delay when fetching from api, not cache
delay && await timers.setTimeout(delay)
CACHE.get(fn).set(key, res)
return res
}
}
export default cacheMethod