-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
384 lines (363 loc) · 10.7 KB
/
cache.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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/**
* wfApi,
* Copyright (C) 2018 Ilkka Kuosmanen
*
* This file is part of wfApi.
*
* wfApi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wfApi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with wfApi. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const https = require("https");
const crypto = require("crypto");
const { getData, getDataNoClean } = require("./lua/getLuaObject");
const CustomError = require("./error").CustomError;
const getLuaObject = getData;
const getLuaObjectNoClean = getDataNoClean;
/**
* @typedef {Object} MetaObject
* @property {number} lastRefresh The last refresh js timestamp.
* @property {number} nRefresh How many times the cache has been refreshed.
* @property {PromiseLike<ArrayBuffer>} hash A hash of the data.
* @property {string} license The license under which the data is licensed.
*/
/**
* @typedef {Object} ResponseObject
* @property {Object} data Response data.
* @property {MetaObject} meta Metadata for the response.
*/
/**
* @typedef {Object} DependencyInfo
* @property {string} module
* @property {Cache} cache
*/
/**
* A cache module class.
*/
class Cache {
/**
* Create a new cache module.
* @param {string} dataUrl Url to the Wikia module.
* @param {string} name Name of the cache module.
* @param {DependencyInfo[]} dependentOn
*/
constructor(dataUrl, name, dependentOn) {
this.data = null;
this.src = null;
this.name = name;
this.lastRefresh = 0;
this.nRefresh = 0;
this.dataUrl = dataUrl;
this.dependentOn = dependentOn;
const dependencyResolve = this.dependentOn
? this.dependentOn.map((dependency) => {
return dependency.cache.get();
})
: [];
Promise.all(dependencyResolve)
.then(() => {
return this.get();
})
.then(() => {
console.log("Cache initialized for: " + this.name);
})
.catch((e) => {
console.log("Failed to initialize cache for: " + this.name);
console.error(e);
});
}
/**
* Find the 'revisions' object from the given object.
* @param {object} data The object from which the 'revisions' object is searched for.
* @returns {object} The data inside revisions object.
* @private
*/
static _findRevisions(data) {
if ("revisions" in data && data.hasOwnProperty("revisions")) {
return data["revisions"][0]["slots"]["main"]["content"];
}
for (let key in data) {
if (!data.hasOwnProperty(key)) {
continue;
}
if (typeof data[key] === "object") {
return this._findRevisions(data[key]);
}
}
return null;
}
/**
* Make a 'GET' request to given Wikia url and get the data inside of the lua object.
* @param {string} url Wikia api url.
* @param {DependencyInfo} dependencies
* @returns {Promise<object, Object>} The content of the lua object.
* @private
*/
_getRequest(url, dependencies) {
return new Promise((resolve, reject) => {
https
.get(url, (res) => {
let data = "";
res.on("data", (d) => {
data += d;
});
res.on("end", () => {
if (data.length === 0) {
return reject(new CustomError("No data."));
}
try {
let parsed = JSON.parse(data.toString());
let revisions = Cache._findRevisions(parsed);
this.src = revisions;
getLuaObject(revisions, dependencies)
.then((data) => {
return resolve(data);
})
.catch((err) => {
return reject(
new CustomError("Failed to get lua data.", err)
);
});
} catch (e) {
return reject(
new CustomError("Failed to parse or find revisions.", e)
);
}
});
})
.on("error", (err) => {
return reject(new CustomError("Failed to retrieve data.", err));
});
});
}
/**
* Create a sha256 hash of the cached data.
* @returns {PromiseLike<ArrayBuffer>} Base64 encoded hash.
*/
createHash() {
let hash = crypto.createHash("sha256");
hash.update(JSON.stringify(this.data));
return hash.digest("base64");
}
/**
* Create a meta data object.
* @returns {MetaObject}
*/
createMeta() {
return {
nRefresh: this.nRefresh,
lastRefresh: this.lastRefresh,
hash: this.createHash(),
license: "CC BY-SA",
};
}
/**
* Get the cached data or refresh the cache.
* @returns {Promise<ResponseObject,Object>} Returns the cached data object.
*/
get() {
return new Promise((resolve, reject) => {
if (
!this.data ||
!this.lastRefresh ||
this.lastRefresh + 1000 * 60 * 60 < Date.now()
) {
if (this.dataUrl) {
this._getRequest(this.dataUrl, this.dependentOn)
.then((data) => {
this.lastRefresh = Date.now();
this.data = data;
this.nRefresh++;
return resolve({
data: this.data,
meta: this.createMeta(),
});
})
.catch((err) => {
return reject(new CustomError("Failed at requesting data.", err));
});
} else {
return reject(
new CustomError("No data url.", {}, { name: this.name })
);
}
} else {
return resolve({
data: this.data,
meta: this.createMeta(),
});
}
});
}
/**
* Get the meta data for cache module
* @returns {Promise<MetaObject, Object>} The metadata object for cache module.
*/
getMeta() {
return new Promise((resolve, reject) => {
this.get()
.then(() => {
return resolve({ meta: this.createMeta() });
})
.catch((e) => {
return reject(new CustomError("Failed to generate meta object.", e));
});
});
}
}
/**
* A cache module class.
*/
class CacheNew {
/**
* Create a new cache module.
* @param {string} dataUrl Url to the Wikia module.
* @param {string} name Name of the cache module.
*/
constructor(dataUrl, name) {
this.data = null;
this.src = null;
this.name = name;
this.lastRefresh = 0;
this.nRefresh = 0;
this.dataUrl = dataUrl;
this.get()
.then(() => {
console.log("Cache initialized for: " + this.name);
})
.catch((e) => {
console.log("Failed to initialize cache for: " + this.name);
console.error(e);
});
}
/**
* Make a 'GET' request to given Wikia url and get the data inside of the lua object.
* @param {string} url Wikia api url.
* @returns {Promise<object, Object>} The content of the lua object.
* @private
*/
_getRequest(url) {
return new Promise((resolve, reject) => {
https
.get(url, (res) => {
let data = "";
res.on("data", (d) => {
data += d;
});
res.on("end", () => {
if (data.length === 0) {
return reject(new CustomError("No data."));
}
try {
let parsed = JSON.parse(data.toString());
this.src = parsed.return;
getLuaObjectNoClean(this.src)
.then((data) => {
return resolve(data);
})
.catch((err) => {
return reject(
new CustomError("Failed to get lua data.", err)
);
});
} catch (e) {
return reject(
new CustomError("Failed to parse or find revisions.", e)
);
}
});
})
.on("error", (err) => {
return reject(new CustomError("Failed to retrieve data.", err));
});
});
}
/**
* Create a sha256 hash of the cached data.
* @returns {PromiseLike<ArrayBuffer>} Base64 encoded hash.
*/
createHash() {
let hash = crypto.createHash("sha256");
hash.update(JSON.stringify(this.data));
return hash.digest("base64");
}
/**
* Create a meta data object.
* @returns {MetaObject}
*/
createMeta() {
return {
nRefresh: this.nRefresh,
lastRefresh: this.lastRefresh,
hash: this.createHash(),
license: "CC BY-SA",
};
}
/**
* Get the cached data or refresh the cache.
* @returns {Promise<ResponseObject,Object>} Returns the cached data object.
*/
get() {
return new Promise((resolve, reject) => {
if (
!this.data ||
!this.lastRefresh ||
this.lastRefresh + 1000 * 60 * 60 < Date.now()
) {
if (this.dataUrl) {
this._getRequest(this.dataUrl)
.then((data) => {
this.lastRefresh = Date.now();
this.data = data;
this.nRefresh++;
return resolve({
data: this.data,
meta: this.createMeta(),
});
})
.catch((err) => {
return reject(new CustomError("Failed at requesting data.", err));
});
} else {
return reject(
new CustomError("No data url.", {}, { name: this.name })
);
}
} else {
return resolve({
data: this.data,
meta: this.createMeta(),
});
}
});
}
/**
* Get the meta data for cache module
* @returns {Promise<MetaObject, Object>} The metadata object for cache module.
*/
getMeta() {
return new Promise((resolve, reject) => {
this.get()
.then(() => {
return resolve({ meta: this.createMeta() });
})
.catch((e) => {
return reject(new CustomError("Failed to generate meta object.", e));
});
});
}
}
module.exports = {
Cache,
CacheNew,
};