-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathredis-store.ts
59 lines (52 loc) · 1.57 KB
/
redis-store.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
import { Store } from './store';
import { Identity } from './types';
class RedisStore implements Store {
public store: any;
private readonly nameSpacedKeyPrefix: string = 'redis-store-id::';
public constructor(redisStoreInstance: unknown) {
this.store = redisStoreInstance;
}
public setForIdentity(
identity: Identity,
timestamps: readonly number[],
windowMs?: number
): Promise<void> {
return new Promise<void>((res, rej): void => {
const expiry = windowMs
? [
'EX',
Math.ceil((Date.now() + windowMs - Math.max(...timestamps)) / 1000),
]
: [];
this.store.set(
[
this.generateNamedSpacedKey(identity),
JSON.stringify([...timestamps]),
...expiry,
],
(err: Error | null): void => {
if (err) return rej(err);
return res();
}
);
});
}
public async getForIdentity(identity: Identity): Promise<readonly number[]> {
return new Promise<readonly number[]>((res, rej): void => {
this.store.get(
this.generateNamedSpacedKey(identity),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(err: Error | null, obj: any): void => {
if (err) {
return rej(err);
}
return res(obj ? JSON.parse(obj) : []);
}
);
});
}
private readonly generateNamedSpacedKey = (identity: Identity): string => {
return `${this.nameSpacedKeyPrefix}${identity.contextIdentity}:${identity.fieldIdentity}`;
};
}
export { RedisStore };