Skip to content

Commit 97e6d9f

Browse files
authored
Add files via upload
1 parent b82c621 commit 97e6d9f

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

ipapi.js

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
2+
'use strict';
3+
4+
var https = require('https');
5+
6+
var API_KEY = '';
7+
8+
var headers = {'user-agent': 'ipapi/ipapi-nodejs/0.2'};
9+
10+
var fieldList = ['ip', 'city', 'region', 'country', 'postal',
11+
'latitude', 'longitude', 'timezone', 'latlong'];
12+
13+
14+
var _request = function(path, callback, isJson){
15+
var options = {
16+
host: 'ipapi.co',
17+
path: path,
18+
headers: headers
19+
};
20+
21+
var req = https.get(options, function(resp){
22+
var body = ''
23+
24+
resp.on('data', function(data){
25+
body += data;
26+
});
27+
28+
resp.on('end', function(){
29+
if (isJson) {
30+
var loc = JSON.parse(body);
31+
callback(loc);
32+
} else {
33+
var loc = body;
34+
callback(loc);
35+
}
36+
});
37+
});
38+
39+
req.on('error', function(e) {
40+
console.log('Request Error ! ' + e.message);
41+
});
42+
};
43+
44+
45+
var location = function(callback, ip, key, field){
46+
var path;
47+
var isField = false;
48+
49+
if (typeof callback !== 'function') {
50+
return 'Callback function is required';
51+
}
52+
53+
if ((typeof field !== 'undefined') && (field !== '')) {
54+
if (fieldList.indexOf(field) === -1) {
55+
return 'Invalid field'
56+
} else {
57+
isField = true;
58+
}
59+
}
60+
61+
if (isField) {
62+
if (typeof ip !== 'undefined') {
63+
path = '/' + ip + '/' + field + '/';
64+
} else {
65+
path = '/' + field + '/';
66+
}
67+
} else {
68+
if (typeof ip !== 'undefined') {
69+
path = '/' + ip + '/json/';
70+
} else {
71+
path = '/json/';
72+
}
73+
}
74+
75+
if ((typeof key !== 'undefined') && (key !== '')){
76+
path = path + '?key=' + key;
77+
} else {
78+
if (API_KEY !== ''){
79+
path = path + '?key=' + API_KEY;
80+
}
81+
}
82+
83+
_request(path, callback, (!isField))
84+
};
85+
86+
87+
/**
88+
* Query location for an IP address
89+
*/
90+
module.exports = {
91+
location : location,
92+
};

0 commit comments

Comments
 (0)