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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
'use strict';
const EventEmitter = require('events');
const retryCodes = [429].concat((process.env.JSON_CACHE_RETRY_CODES || '')
.split(',').map(code => parseInt(code.trim(), 10)));
const defaultOpts = {
parser: JSON.parse,
promiseLib: Promise,
logger: console,
delayStart: false,
opts: {},
maxListeners: 10,
useEmitter: false,
maxRetry: 1,
integrity: () => true,
};
class JSONCache extends EventEmitter {
constructor(url, timeout, options) {
super();
options = {
...defaultOpts,
...options,
};
const {
parser, promiseLib, logger, delayStart, opts, maxListeners, useEmitter, maxRetry, integrity,
} = options;
this.url = url;
this.protocol = this.url.startsWith('https') ? require('https') : require('http');
this.maxRetry = maxRetry;
this.timeout = timeout || 60000;
this.currentData = null;
this.updating = null;
this.Promise = promiseLib;
this.parser = parser;
this.hash = null;
this.logger = logger;
this.delayStart = delayStart;
this.opts = opts;
this.useEmitter = useEmitter;
this.integrity = integrity;
if (useEmitter) {
this.setMaxListeners(maxListeners);
}
if (!delayStart) {
this.startUpdating();
}
}
getData() {
if (this.delayStart && !this.currentData && !this.updating) {
this.startUpdating();
}
if (this.updating) {
return this.updating;
}
return this.Promise.resolve(this.currentData);
}
getDataJson() {
return this.getData();
}
update() {
this.updating = this.httpGet().then(async (data) => {
const parsed = this.parser(data, this.opts);
if (!this.integrity(parsed)) return this.currentData;
this.currentData = parsed;
if (this.useEmitter) {
setTimeout(async () => this.emit('update', await this.currentData), 2000);
}
this.updating = null;
return this.currentData;
}).catch((err) => {
this.updating = null;
throw err;
});
}
httpGet() {
return new this.Promise((resolve) => {
const request = this.protocol.get(this.url, (response) => {
this.logger.debug(`beginning request to ${this.url}`);
const body = [];
if (response.statusCode < 200 || response.statusCode > 299) {
if ((response.statusCode > 499 || retryCodes.includes(response.statusCode))
&& this.retryCount < this.maxRetry) {
this.retryCount += 1;
setTimeout(() => this.httpGet().then(resolve).catch(this.logger.error), 1000);
} else {
this.logger.error(`${response.statusCode}: Failed to load ${this.url}`);
resolve('[]');
}
} else {
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
this.retryCount = 0;
resolve(body.join(''));
});
}
});
request.on('error', (err) => {
this.logger.error(`${err.statusCode}: ${this.url}`);
resolve('[]');
});
});
}
startUpdating() {
this.updateInterval = setInterval(() => this.update(), this.timeout);
this.update();
}
stop() {
clearInterval(this.updateInterval);
}
stopUpdating() {
this.stop();
}
}
module.exports = JSONCache;