/
index.js
41 lines (36 loc) · 818 Bytes
/
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
const got = require('got');
const fs = require('fs');
function openCache(file) {
try {
return require(file);
} catch (ex) {
return {};
}
}
function flush(file, content) {
if (!file) throw new Error('Missing file cache');
fs.writeFileSync(file, JSON.stringify(content, null, ' '));
}
module.exports = (cacheFile) => {
let cache = openCache(cacheFile);
return {
got: async (url, options) => {
if (url in cache) {
return {
url,
body: cache[url],
};
}
const response = await got(url, options);
cache[url] = response.body;
// handles redirect
cache[response.url] = response.body;
flush(cacheFile, cache);
return response;
},
clear() {
cache = {};
flush(cacheFile, cache);
},
};
};