This repository has been archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
redis_big_segment_store.js
65 lines (54 loc) · 1.97 KB
/
redis_big_segment_store.js
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
const base = require('./redis_base');
const { promisify } = require('util');
const keyLastUpToDate = 'big_segments_synchronized_on';
const keyUserInclude = 'big_segment_include:';
const keyUserExclude = 'big_segment_exclude:';
function RedisBigSegmentStore(options) {
return config => bigSegmentStoreImpl(options || {}, config.logger);
// Note, config.logger is guaranteed to be defined - the SDK will have provided a default one if necessary
}
function bigSegmentStoreImpl(options, logger) {
const state = base.initState(options, logger);
const client = state.client;
const prefix = state.prefix;
const store = {};
// Pre-promisify these methods for efficiency. Note that we have to add .bind(client) to each method
// when using promisify, because the redis client methods don't work without a "this" context.
const clientGet = promisify(client.get.bind(client));
const clientSmembers = promisify(client.smembers.bind(client));
store.getMetadata = async () => {
const value = await clientGet(prefix + keyLastUpToDate);
return { lastUpToDate: value === null || value === undefined || value === '' ? undefined : parseInt(value) };
};
store.getUserMembership = async userHash => {
const includedRefs = await promisify(clientSmembers)(prefix + keyUserInclude + userHash);
const excludedRefs = await promisify(clientSmembers)(prefix + keyUserExclude + userHash);
if ((!includedRefs || !includedRefs.length) && (!excludedRefs || !excludedRefs.length)) {
return null;
}
const membership = {};
if (excludedRefs) {
for (const ref of excludedRefs) {
membership[ref] = false;
}
}
if (includedRefs) {
for (const ref of includedRefs) {
membership[ref] = true;
}
}
return membership;
};
store.close = () => {
if (state.stopClientOnClose) {
client.quit();
}
};
return store;
}
module.exports = {
RedisBigSegmentStore,
keyLastUpToDate,
keyUserInclude,
keyUserExclude,
};