This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skyhook.js
111 lines (94 loc) · 2.29 KB
/
skyhook.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
Name: skyhook-api
Description: Lookup IP-address details at Skyhook API
Author: Franklin van de Meent (https://frankl.in)
Source: https://github.com/fvdm/nodejs-skyhook
Feedback: https://github.com/fvdm/nodejs-skyhook/issues
License: Unlicense (Public Domain)
See https://github.com/fvdm/nodejs-skyhook/raw/master/LICENSE
*/
'use strict';
const httpreq = require ('httpreq');
let app = {
user: null,
key: null,
timeout: 5000
};
/**
* Process API response
*
* @callback callback
* @param err {Error, null} - Error
* @param res {object} - Response data
* @param callback {function} - `function (err, data) {}`
* @return {void}
*/
function processResponse (err, res, callback) {
let data = res && res.body || '';
let error = null;
try {
data = JSON.parse (data);
} catch (e) {
error = new Error ('invalid data');
error.data = data;
}
if (err) {
error = new Error ('request failed');
error.error = err;
}
if (data.error) {
error = new Error ('api error');
error.code = data.error.code;
error.text = data.error.message;
}
if (error) {
error.statusCode = res && res.statusCode;
callback (error);
} else {
data = data.data || data;
callback (null, data);
}
}
/**
* Communicate with API
*
* @callback callback
* @param ip {string} - IP-address to lookup
* @param callback {function} - `function (err, data) {}`
* @return {void}
*/
function getIP (ip, callback) {
const options = {
url: 'https://context.skyhookwireless.com/accelerator/ip',
method: 'GET',
timeout: app.timeout,
parameters: {
version: '2.0',
ip: ip,
user: app.user,
key: app.key,
timestamp: Math.round (Date.now () / 1000)
},
headers: {
'User-Agent': 'npmjs.com/package/skyhook-api',
'Accept': 'application/json'
}
};
httpreq.doRequest (options, (err, res) => {
processResponse (err, res, callback);
});
}
/**
* Module interface
*
* @param user {string} - Username/email
* @param key {string} - API key
* @param [timeout = 5000] - Request time out in ms, 1000 = 1 sec
* @return getIP {function}
*/
module.exports = (user, key, timeout) => {
app.user = user;
app.key = key;
app.timeout = timeout || app.timeout;
return getIP;
};