-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (49 loc) · 1.35 KB
/
index.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
"use strict";
const ws = require("ws");
const R = require("ramda");
const url = require("url");
let config = {};
const initializeConfigUpdate = (conf) => {
let ping;
let retryNumOfTimes = 0;
const connect = (resolve, reject) => {
const webSocket = new ws(url.resolve(conf.requestUrl, conf.environment));
webSocket.on("open", () => {
retryNumOfTimes = 0;
webSocket.send(conf.environment);
ping = setInterval(() => {
webSocket.ping();
}, 15000);
});
webSocket.on("message", (message) => {
const data = JSON.parse(message);
if (data.initialConfig) {
Object.assign(config, JSON.parse(data.initialConfig));
resolve(config);
} else if (data.environment === conf.environment) {
Object.assign(config, JSON.parse(data.config));
}
});
webSocket.on("error", (error) => {
console.error(error);
reject(error);
});
webSocket.on("close", () => {
clearInterval(ping);
setTimeout(connect, Math.ceil(Math.pow(Math.E, retryNumOfTimes)) * 100, resolve, reject);
retryNumOfTimes += 1;
});
};
return new Promise(connect);
};
const getConfig = (path, def) => {
const confValue = R.path(path, config);
if (confValue !== undefined) {
return confValue;
}
return def;
};
module.exports = {
initializeConfigUpdate,
getConfig
};