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 65
/
polling.js
70 lines (58 loc) · 1.88 KB
/
polling.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
65
66
67
68
69
70
const errors = require('./errors');
const messages = require('./messages');
const dataKind = require('./versioned_data_kind');
function PollingProcessor(config, requestor) {
const processor = {},
featureStore = config.featureStore,
intervalMs = config.pollInterval * 1000;
let stopped = false;
let pollTask;
function poll(maybeCallback) {
const cb = maybeCallback || function () {};
if (stopped) {
return;
}
config.logger.debug('Polling LaunchDarkly for feature flag updates');
requestor.requestAllData((err, respBody) => {
if (err) {
if (err.status && !errors.isHttpErrorRecoverable(err.status)) {
const message = messages.httpErrorMessage(err, 'polling request');
config.logger.error(message);
cb(new errors.LDPollingError(message));
processor.stop();
} else {
config.logger.warn(messages.httpErrorMessage(err, 'polling request', 'will retry'));
}
} else {
if (respBody) {
const allData = JSON.parse(respBody);
const initData = {};
initData[dataKind.features.namespace] = allData.flags;
initData[dataKind.segments.namespace] = allData.segments;
featureStore.init(initData, () => {
cb();
});
}
// There wasn't an error but there wasn't any new data either, so just keep polling
}
});
}
processor.start = cb => {
if (!pollTask && !stopped) {
pollTask = setInterval(() => poll(cb), intervalMs);
// setInterval always waits for the delay before firing the first time, but we want to do an initial poll right away
poll(cb);
}
};
processor.stop = () => {
stopped = true;
if (pollTask) {
clearInterval(pollTask);
}
};
processor.close = () => {
processor.stop();
};
return processor;
}
module.exports = PollingProcessor;