-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (46 loc) · 1.08 KB
/
index.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
/**
* Created by Rohail Najam on 2/10/2017.
*/
'use strict';
const ipRegex = require('ip-regex');
const request = require('request');
const iplocateServiceUrl = "http://freegeoip.net/json/";
/**
* Get Location information of the IP
* @param {number} Ip
* @return {JSON} location Object
*/
function ipToLocation(ip) {
return new Promise(function (resolve, reject) {
if (!ipRegex({exact: true}).test(ip)) {
let error = {message : "Invalid Ip Address"};
reject(error)
}else {
request(iplocateServiceUrl+ ip,function (err, resp, body) {
if(err){
reject(err)
}else {
resolve(JSON.parse(body))
}
});
}
});
}
/**
* Middleware Function for the IP
* @param {Request} req
* @param {Response} res
* @param {function} next
*/
function middlewareFunction (req,res,next){
return ipToLocation(req.ip)
.then(function (location) {
req.location = location;
next();
})
.catch(function (error) {
req.locationError = error;
next();
})
}
module.exports = middlewareFunction;