forked from sumcoinlabs/sumcoin-nodes-map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocations.js
executable file
·60 lines (53 loc) · 1.6 KB
/
locations.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
const axios = require('axios');
const CachemanFile = require('cacheman-file');
const cache = new CachemanFile({tmpDir: '.cache', ttl: 24*3600,});
const getPeers = async () => {
try {
params = {
"method": "getpeerinfo",
"params": [],
"id": "foo"
}
const res = await axios.post('http://user:password@127.0.0.1:3332/', params);
//console.log(res.data.result);
if (!res.data.result) throw new Error('Missing peers.');
console.log(`${res.data.result.length} peers found`);
return res.data.result;
} catch (e) {
console.log('Can\'t get peers');
throw e;
}
};
const getLocation = async (ip) => new Promise((resolve) => {
cache.get(ip, async (err, value) => {
if (value) {
return resolve(value);
}
try {
const res = await axios.get(`http://127.0.0.1:8080/json/${ip}`);
cache.set(ip, res.data, 24*3600);
resolve(res.data);
} catch (e) {
console.log('Can\'t get location', e);
}
});
});
const getLocations = async () => {
return getPeers().then(result => Promise.all(result.map(result => {
const [ip, ] = result.addr.split(':');
return getLocation(ip);
})));
};
const cacheLocations = async () => {
const locations = await getLocations();
cache.set('locations', JSON.stringify(locations), 100)
};
const getCachedLocations = () => new Promise((resolve) => {
cache.get('locations', (err, value) => {
resolve(value ? value : []);
});
});
module.exports = {
getCachedLocations,
cacheLocations,
};