-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
50 lines (40 loc) · 1.21 KB
/
index.js
File metadata and controls
50 lines (40 loc) · 1.21 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
/*
Name: google-geolocation - index.js
Description: Google Maps Geolocation API for Node.js (unofficial)
Author: Franklin (https://frankl.in)
License: Unlicense (public domain, see LICENSE file)
Source & docs: https://github.com/fvdm/nodejs-geolocation
*/
/**
* Perform geolocation request
*
* @param {object} params Parameters
* @param {string} params.key API key
* @param {number} [params.timeout=5000] Request timeout in ms
*
* @return {Promise<object>}
*/
module.exports = async ( {
key,
timeout = 5000,
} ) => {
delete arguments[0].key;
delete arguments[0].timeout;
const url = `https://www.googleapis.com/geolocation/v1/geolocate?key=${key}`;
const options = {
method: 'POST',
body: JSON.stringify( arguments[0] ),
signal: AbortSignal.timeout( timeout ),
};
const res = await fetch( url, options );
const data = await res.json();
if ( data.error ) {
const error = new Error( data.error.message );
error.code = data.error.code;
error.reason = data.error.details[0].reason;
error.details = data.error.details;
error.errors = data.error.errors;
throw error;
}
return data;
};