generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeo.js
More file actions
69 lines (62 loc) · 2.04 KB
/
geo.js
File metadata and controls
69 lines (62 loc) · 2.04 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
const ENDPOINT = 'https://api.ipgeolocation.io/ipgeo';
const ENV_NAME = 'IPGEOLOCATION_KEY';
const cache = new Map();
let warned = false;
/**
* Adds a `geo` object containing geoip data to the request context object.
*
* @param {string} [apiKey=process.env.IPGEOLOCATION_KEY] The API key for `api.ipgeolocation.io`, defaulting to one provided by an environment variable.
* @returns {Function} The middleware context modifying callback.
*/
export function useGeo(apiKey = process.env[ENV_NAME]) {
/**
* @async
* @param {Request} req Unused request object.
* @param {object} context The context object to add geoip data to.
*/
return async function(req, context) {
if (typeof context.ip !== 'string' || context.signal.aborted) {
return;
} else if (cache.has(context.ip)) {
context.geo = cache.get(context.ip);
} else if (typeof apiKey === 'string') {
const url = new URL(ENDPOINT);
url.searchParams.set('apiKey', apiKey);
// Defaults to own IP if not provided
if (context.ip !== '::1' && context.ip !== '127.0.0.1' && context.ip !== '0.0.0.0') {
url.searchParams.set('ip', context.ip);
}
const resp = await fetch(url, {
headers: { Accept: 'application/json' },
signal: context.signal,
}).catch(err => {
console.error(err);
return Response.error();
});
if (resp.ok) {
const {
city,
country_name: name,
country_code2: code,
latitude,
longitude,
zipcode: postalCode,
time_zone: { name: timezone },
state_code,
state_prov,
} = await resp.json();
const geo = Object.freeze({
city, latitude, longitude, postalCode, timezone,
country: { name, code },
subdivision: { name: state_prov, code: state_code },
});
cache.set(context.ip, geo);
context.geo = Object.freeze(geo);
}
} else if (! warned) {
console.warn('No API key given. Visit https://ipgeolocation.io/ if you need to create an API key.');
warned = true;
}
};
}
export default typeof process.env[ENV_NAME] === 'string' ? useGeo(process.env[ENV_NAME]) : () => null;