-
Notifications
You must be signed in to change notification settings - Fork 1
/
locations.js
55 lines (48 loc) · 1.59 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
const axios = require('axios');
const CachemanFile = require('cacheman-file');
const cache = new CachemanFile({tmpDir: '.cache', ttl: 30*24*3600,});
const getPeers = async () => {
try {
const res = await axios.get('https://seed219.cryptoluka.cl/peers');
if (!res.data.peers) throw new Error('Missing peers.');
console.log(`${res.data.peers.length} peers found`);
return res.data.peers;
} 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 {
console.log(`Request geolocation for IP: ${ip}`);
const res = await axios.get(`http://api.ipstack.com/${ip}?access_key=f260bbb194ebfd8c26883e512580fae5&output=json&legacy=1`);
cache.set(ip, res.data, 30*24*3600);
resolve(res.data);
} catch (e) {
console.log('Can\'t get location', e);
}
});
});
const getLocations = async () => {
return getPeers().then(peers => Promise.all(peers.map(peer => {
const [ip, ] = peer.split(':');
return getLocation(ip);
})));
};
const cacheLocations = async () => {
const locations = await getLocations();
cache.set('locations', JSON.stringify(locations), 180);
};
const getCachedLocations = () => new Promise((resolve) => {
cache.get('locations', (err, value) => {
resolve(value ? value : []);
});
});
module.exports = {
getCachedLocations,
cacheLocations,
};