-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.ts
112 lines (98 loc) · 2.93 KB
/
cache.ts
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-shadow */
import { boolean } from 'zod'
import { getRedisClient } from './redis-utils/get-client'
import { RedisStore } from './store/redis-store'
import { currentTimestamp } from './utils'
import Debugger from 'debug'
const debugError = Debugger('apis:cache:error')
interface Options {
cacheSeconds: number
tags?: string[]
}
const cache = new RedisStore({
client: getRedisClient(),
updateCache: true
})
type InferResultType<R> = R extends { result: infer T } ? T : R
export async function cacheFunctionResult<T, F extends (...args: any[]) => any>(
fn: F,
args: Parameters<F>,
options?: Options
): Promise<CacheResponse<InferResultType<Awaited<ReturnType<F>>>>> {
const { tags = [], cacheSeconds = 0 } = options || {}
const key = [
'cacheFunctionResult',
...tags,
fn.name,
...args.map((a) => String(a))
].join('-')
return cache.getOrSet(key, () => generateResponse(fn, args, cacheSeconds), cacheSeconds)
}
function doesResultExtendsResponse(
result: any
): result is { result: any; cacheTimestamp?: number } {
return typeof result === 'object' && result !== null && 'result' in result
}
type CacheMeta = {
cacheTimestamp: number
cacheSeconds: number
}
export type CacheResponse<T> = CacheMeta &
(
| { result: T }
| {
error: string
status: number
}
)
// includes error in the cache function output,
// this is needed for preventing someone to abuse
// an endpoint which does not cache due to revert
async function generateResponse<R, F extends (...args: any[]) => Promise<R>>(
fn: F,
args: Parameters<F>,
cacheSeconds: number
): Promise<CacheResponse<InferResultType<R>>> {
try {
const result = await fn(...args)
if (doesResultExtendsResponse(result)) {
// allows to override `cacheTimestamp`
return {
...result,
cacheTimestamp: Math.min(
result.cacheTimestamp ?? Number.MAX_SAFE_INTEGER,
currentTimestamp()
),
cacheSeconds
}
} else {
return { result: result as any, cacheTimestamp: currentTimestamp(), cacheSeconds }
}
} catch (error: any) {
debugError(JSON.stringify(error))
if (error instanceof TypeError) {
console.error('caught in generateResponse', error)
}
// cache the error resp (to prevent DoS, hitting with an input which reverts in middle
if (error.status && error.status < 500) {
// cache normal errors for 15 seconds
return {
error: error.message,
status: error.status,
cacheTimestamp: currentTimestamp(),
cacheSeconds: Math.min(cacheSeconds, 15)
}
} else {
return {
error: error.message,
status: error.status,
cacheTimestamp: currentTimestamp(),
cacheSeconds: Math.min(cacheSeconds, 15)
}
}
}
}
export async function flushall() {
await cache.client.flushall()
}