forked from J-Chaniotis/external-ip
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequests.js
93 lines (85 loc) · 2.31 KB
/
requests.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
"use strict";
let request = require("request");
let utils = require("./utils");
exports = module.exports = {
/**
* initialized services
* @type {Array}
*/
services: [],
/**
* setup services by configuration
* @param {*} config
* @return {Array}
*/
setup: config => {
return (exports.services = exports.initializeServices(config));
},
/**
* initialize services and create a call wrapper
* @param {*} config
* @return {Array}
*/
initializeServices: config => {
return config.services.map(url => exports.factory(config, url));
},
/**
* factory helper to create wrapper for each service
* @param {object} config
* @param {string} url
* @return {function}
*/
factory: (config, url) => {
return () => {
return exports
.requestBody(request, config, url)
.then(exports.validateBody)
.catch(err => {
return Promise.reject(err + " (" + url + ")");
});
};
},
/**
* request body from service
* @param {object} request
* @param {object} config
* @param {string} url
* @return {Promise}
*/
requestBody: (request, config, url) => {
return new Promise((resolve, reject) => {
request.get({
url : url,
timeout : config.timeout,
agent : config.agent || undefined,
headers : {
"User-Agent": config.userAgent
}
}, (err, res, body) => {
if( err ) {
reject(err.message || err);
}
else {
resolve(body);
}
});
});
},
/**
* validate response body to be an ip address
* @param {string|*} body
* @return {Promise}
*/
validateBody: body => {
return new Promise((resolve, reject) => {
// if the body is null use an empty string
body = (body || "").toString().replace("\n", "");
if( utils.isIP(body) ) {
resolve(body);
}
else {
reject("invalid response (it's not an IP)");
}
});
}
};