1 | class CacheRedis {
|
2 | constructor({ client, prefixKey, expirationTime, isJson, deserializeFunc }) {
|
3 | this.client = client;
|
4 | this.prefixKey = prefixKey;
|
5 | this.expirationTime = expirationTime;
|
6 | this.isJson = isJson;
|
7 | this.deserializeFunc = deserializeFunc;
|
8 | }
|
9 |
|
10 | formatKey(key) {
|
11 | if (this.prefixKey) {
|
12 | return `${this.prefixKey}:${key}`;
|
13 | }
|
14 |
|
15 | return key;
|
16 | }
|
17 |
|
18 | async deserialize(data) {
|
19 | if (this.deserializeFunc) {
|
20 | return this.deserializeFunc(data);
|
21 | }
|
22 |
|
23 | return data;
|
24 | }
|
25 |
|
26 | async remove(key) {
|
27 | const formattedKey = this.formatKey(key);
|
28 | const value = await this.client.remove(formattedKey);
|
29 | return this.deserialize(value);
|
30 | }
|
31 |
|
32 | async get(key) {
|
33 | const formattedKey = this.formatKey(key);
|
34 | const value = await this.client.getValue(formattedKey, this.isJson);
|
35 | return this.deserialize(value);
|
36 | }
|
37 |
|
38 | async set(key, value) {
|
39 | const formattedKey = this.formatKey(key);
|
40 | if (this.expirationTime) {
|
41 | return this.client.setValueWithExpirationTime(
|
42 | formattedKey,
|
43 | value,
|
44 | this.isJson,
|
45 | this.expirationTime,
|
46 | );
|
47 | }
|
48 | return this.client.setValue(formattedKey, value, this.isJson);
|
49 | }
|
50 | }
|
51 |
|
52 | module.exports = { CacheRedis };
|