-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequests.mjs
53 lines (41 loc) · 1.12 KB
/
requests.mjs
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
import fetch from 'node-fetch';
import { readFile, writeFile, stat } from 'fs/promises';
import crypto from 'crypto';
const hash = str => {
let shasum = crypto.createHash('sha1')
shasum.update(str)
return shasum.digest('hex')
}
const _makeReqAndSave = async (url, urlhash) => {
console.log(url);
let data = await fetch(url).then(res => {
if (!res.ok) {
throw Error(url+' '+res.status);
}
return res.text();
});
await writeFile('./cache/'+urlhash, data);
await sleep(210);
return data;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const makeReq = async (url) => {
let urlhash = hash(url);
let statRes;
try {
statRes = await stat('./cache/'+urlhash);
} catch (err) {
if (err.code === 'ENOENT') {
return _makeReqAndSave(url, urlhash);
}
throw err;
}
if (Date.now() - statRes.mtimeMs > 9*3600*1000) {
return _makeReqAndSave(url, urlhash);
}
let data = await readFile('./cache/'+urlhash);
return data;
}
export default makeReq;