-
Notifications
You must be signed in to change notification settings - Fork 11
/
ipapi.js
92 lines (72 loc) · 1.92 KB
/
ipapi.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
'use strict';
var https = require('https');
var API_KEY = '';
var headers = {'user-agent': 'ipapi/ipapi-nodejs/0.4.1'};
var fieldList = ['ip', 'city', 'region', 'country', 'postal',
'latitude', 'longitude', 'timezone', 'latlong'];
var _request = function(path, callback, isJson){
var options = {
host: 'ipapi.co',
path: path,
headers: headers
};
var req = https.get(options, function(resp){
var body = ''
resp.on('data', function(data){
body += data;
});
resp.on('end', function(){
if (isJson) {
var loc = JSON.parse(body);
callback(loc);
} else {
var loc = body;
callback(loc);
}
});
});
req.on('error', function(e) {
callback(new Error(e));
});
};
var location = function(callback, ip, key, field){
var path;
var isField = false;
if (typeof callback !== 'function') {
return 'Callback function is required';
}
if ((typeof field !== 'undefined') && (field !== '')) {
if (fieldList.indexOf(field) === -1) {
return 'Invalid field'
} else {
isField = true;
}
}
if (isField) {
if (typeof ip !== 'undefined') {
path = '/' + ip + '/' + field + '/';
} else {
path = '/' + field + '/';
}
} else {
if (typeof ip !== 'undefined') {
path = '/' + ip + '/json/';
} else {
path = '/json/';
}
}
if ((typeof key !== 'undefined') && (key !== '')){
path = path + '?key=' + key;
} else {
if (API_KEY !== ''){
path = path + '?key=' + API_KEY;
}
}
_request(path, callback, (!isField))
};
/**
* Query location for an IP address
*/
module.exports = {
location : location,
};