-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSegmentsCacheInRedis.ts
More file actions
58 lines (49 loc) · 2.03 KB
/
SegmentsCacheInRedis.ts
File metadata and controls
58 lines (49 loc) · 2.03 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
import { ILogger } from '../../logger/types';
import { isNaNNumber } from '../../utils/lang';
import { LOG_PREFIX } from '../inLocalStorage/constants';
import { KeyBuilderSS } from '../KeyBuilderSS';
import { ISegmentsCacheAsync } from '../types';
import type { RedisAdapter } from './RedisAdapter';
export class SegmentsCacheInRedis implements ISegmentsCacheAsync {
private readonly log: ILogger;
private readonly redis: RedisAdapter;
private readonly keys: KeyBuilderSS;
constructor(log: ILogger, keys: KeyBuilderSS, redis: RedisAdapter) {
this.log = log;
this.redis = redis;
this.keys = keys;
}
/**
* Update the given segment `name` with the lists of `addedKeys`, `removedKeys` and `changeNumber`.
* The returned promise is resolved if the operation success, with `true` if the segment was updated (i.e., some key was added or removed),
* or rejected if it fails (e.g., Redis operation fails).
*/
update(name: string, addedKeys: string[], removedKeys: string[], changeNumber: number) {
const segmentKey = this.keys.buildSegmentNameKey(name);
return Promise.all([
addedKeys.length && this.redis.sadd(segmentKey, addedKeys),
removedKeys.length && this.redis.srem(segmentKey, removedKeys),
this.redis.set(this.keys.buildSegmentTillKey(name), changeNumber + '')
]).then(() => {
return addedKeys.length > 0 || removedKeys.length > 0;
});
}
isInSegment(name: string, key: string) {
return this.redis.sismember(
this.keys.buildSegmentNameKey(name), key
).then(matches => matches !== 0);
}
getChangeNumber(name: string) {
return this.redis.get(this.keys.buildSegmentTillKey(name)).then((value: string | null) => {
const i = parseInt(value as string, 10);
return isNaNNumber(i) ? undefined : i;
}).catch((e) => {
this.log.error(LOG_PREFIX + 'Could not retrieve changeNumber from segments storage. Error: ' + e);
return undefined;
});
}
// @TODO remove or implement. It is not being used.
clear() {
return Promise.resolve();
}
}