-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
132 lines (120 loc) · 3.57 KB
/
Copy pathcache.ts
File metadata and controls
132 lines (120 loc) · 3.57 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import {FastifyInstance} from 'fastify';
import fp from 'fastify-plugin';
import Redis from 'ioredis';
import NodeCache from 'node-cache';
export interface ICache {
get<T = unknown>(key: string): Promise<T | null>;
set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void>;
delete(key: string): Promise<void>;
has(key: string): Promise<boolean>;
clear(): Promise<void>;
raw: Redis | NodeCache;
}
export default fp(
async (fastify: FastifyInstance) => {
let cacheWrapper: ICache;
const cacheConfig = fastify.appConfig?.infrastructure?.cache;
if (
cacheConfig &&
cacheConfig.engine === 'redis' &&
cacheConfig.connection &&
cacheConfig.connection.url
) {
// Use Redis
const redis = new Redis(cacheConfig.connection.url, {
connectTimeout: cacheConfig.timeout ?? 5000,
retryStrategy: times => Math.min(times * 50, 2000),
maxRetriesPerRequest: 3,
});
redis.on('error', err => {
fastify.log.error(`Redis connection error: ${err.message}`);
});
redis.on('connect', () => {
fastify.log.info('Redis connection established');
});
redis.on('ready', () => {
fastify.log.info('Redis client ready');
});
try {
await redis.ping();
fastify.log.info(
`Redis connection successful to ${cacheConfig.connection.url}`,
);
} catch (err) {
fastify.log.error(`Failed to connect to Redis: ${err}`);
throw err;
}
cacheWrapper = {
async get<T>(key: string) {
const val = await redis.get(key);
if (!val) return null;
try {
return JSON.parse(val) as T;
} catch {
return val as unknown as T;
}
},
async set<T>(key: string, value: T, ttlSeconds?: number) {
const strVal =
typeof value === 'string' ? value : JSON.stringify(value);
if (ttlSeconds) {
await redis.set(key, strVal, 'EX', ttlSeconds);
} else {
await redis.set(key, strVal);
}
},
async delete(key: string) {
await redis.del(key);
},
async has(key: string) {
const exists = await redis.exists(key);
return exists > 0;
},
async clear() {
await redis.flushdb();
},
raw: redis,
};
fastify.addHook('onClose', async () => {
fastify.log.info('Closing Redis connection...');
await redis.quit();
fastify.log.info('Redis connection closed.');
});
} else {
// Use node-cache
fastify.log.info('Using node-cache for caching');
const nodeCache = new NodeCache();
cacheWrapper = {
async get<T>(key: string) {
const val = nodeCache.get<T>(key);
return val === undefined ? null : val;
},
async set<T>(key: string, value: T, ttlSeconds?: number) {
if (ttlSeconds) {
nodeCache.set(key, value, ttlSeconds);
} else {
nodeCache.set(key, value);
}
},
async delete(key: string) {
nodeCache.del(key);
},
async has(key: string) {
return nodeCache.has(key);
},
async clear() {
nodeCache.flushAll();
},
raw: nodeCache,
};
fastify.addHook('onClose', async () => {
fastify.log.info('Closing node-cache...');
nodeCache.close();
});
}
fastify.decorate('cache', cacheWrapper);
},
{
name: 'cache-plugin',
},
);