-
-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathredis.ts
70 lines (60 loc) · 1.62 KB
/
redis.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
import { createLogger } from '@surgio/logger'
import Redis from 'ioredis'
import { CACHE_KEYS } from './constant'
const logger = createLogger({ service: 'surgio:redis' })
const prepareRedis = () => {
let client: Redis | null = null
let redisURL: string | null = null
return {
hasRedis: () => !!client,
createRedis(_redisURL: string, customRedis?: any): Redis {
if (client && redisURL) {
logger.debug('Redis client already created with URL: %s', redisURL)
return client
}
redisURL = _redisURL
if (customRedis) {
client = new customRedis(_redisURL)
} else {
client = new Redis(
_redisURL.includes('?')
? `${_redisURL}&family=0`
: `${_redisURL}?family=0`,
)
}
return client as Redis
},
getRedis(): Redis {
if (!client) {
throw new Error('Redis client is not initialized')
}
return client
},
async destroyRedis(): Promise<void> {
if (client) {
await client.quit()
client = null
redisURL = null
}
},
async cleanCache(): Promise<void> {
if (!client) {
return
}
const keysToRemove = await Promise.all(
Object.keys(CACHE_KEYS).map((key) => {
if (!client) return
return client.keys(`${CACHE_KEYS[key as keyof typeof CACHE_KEYS]}:*`)
}),
)
await Promise.all(
keysToRemove.map((keys) => {
if (!client || !keys || !keys.length) return
return client.del(keys)
}),
)
},
}
}
const redis = prepareRedis()
export default redis