-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (66 loc) · 1.94 KB
/
Copy pathserver.js
File metadata and controls
82 lines (66 loc) · 1.94 KB
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
const express = require('express');
const app = express();
const port = 3000;
cachedIps = new Map();
app.use(express.json());
app.get('/ip/:ip', async (req, res) => {
const ip = req.params.ip;
if (cachedIps.has(ip)) {
// console.log('Cache hit for IP:', ip);
res.json(cachedIps.get(ip));
} else {
getIpInfo(ip).then(data => {
if(data.status !== 'success') {
return res.status(400).json(data);
}
let anon = data.proxy || data.hosting || false;
let idata = {
anon: anon,
status: data.status,
ip: ip,
isp: data.isp
};
cachedIps.set(ip, idata);
res.json(idata);
});
}
});
app.get('/cached-ips/keys', (req, res) => {
res.json(Array.from(cachedIps.keys()));
});
app.get('/cached-ips/values', (req, res) => {
res.json(Array.from(cachedIps.values()));
});
app.get('/cached-ips/size', (req, res) => {
res.json({ size: cachedIps.size });
});
app.get('/clear-cache', (req, res) => {
cachedIps.clear();
res.json({ status: 'success'})
});
async function getIpInfo(ip) {
try {
const resp = await fetch('http://ip-api.com/json/' + ip + '?fields=17023488');
if (!resp.ok) {
return { status: 'failed', message: 'bad status ' + resp.status };
}
const text = await resp.text();
if (!text) {
return { status: 'failed', message: 'empty body' };
}
try {
return JSON.parse(text);
} catch {
return { status: 'failed', message: 'invalid json' };
}
} catch (err) {
return { status: 'failed', message: err.message };
}
}
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ status: 'failed', message: err.message });
});
app.listen(port, () => {
console.log(`Listening at ${port}`);
});