-
Notifications
You must be signed in to change notification settings - Fork 5
/
request.js
123 lines (109 loc) · 2.8 KB
/
request.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
112
113
114
115
116
117
118
119
120
121
122
123
var axios = require("axios");
// var http = require("http");
// var https = require("https");
//
// var FormData = require("form-data");
/**
* Incoming config:
*
* {
* "url": "",
* "method": "",
* "headers": {},
* "qs": {},
* "data": "" | {},
* "json": {}
* }
*
* Callback is (err, response).
*
* Where response is the Axios response object.
*
* @param config
* @param callback
*/
module.exports = function(config, callback)
{
// request config - https://github.com/request/request#requestoptions-callback
// axios config - https://www.npmjs.com/package/axios
if (!callback) {
callback = function(err, response, data) {
// nothing
};
}
var requestConfig = {};
requestConfig.url = config.uri || config.url;
requestConfig.method = config.method || "get";
requestConfig.headers = {};
if (!config) {
config = {};
}
if (!config.headers) {
config.headers = {};
}
for (var k in config.headers)
{
var v = config.headers[k];
if (v)
{
requestConfig.headers[k.trim().toLowerCase()] = v;
}
}
// support for FormData headers
// copy form data headers
if (config.data && config.data.getHeaders)
{
var formDataHeaders = config.data.getHeaders();
for (var k in formDataHeaders)
{
var v = formDataHeaders[k];
requestConfig.headers[k] = v;
}
}
if (config.qs) {
requestConfig.params = config.qs;
}
if (config.json) {
requestConfig.data = config.json;
if (!requestConfig.headers["content-type"]) {
requestConfig.headers["content-type"] = "application/json";
}
}
if (config.data)
{
requestConfig.data = config.data;
if (!requestConfig.headers["content-type"])
{
if (!requestConfig.data)
{
if (requestConfig.data.getHeaders)
{
// assume this is a FormData and skip
}
else if (typeof(requestConfig.data) === "object")
{
// send as json
requestConfig.headers["content-type"] = "application/json";
}
}
}
}
if (config.responseType) {
requestConfig.responseType = config.responseType;
}
/*
if (requestConfig.url.toLowerCase().indexOf("https:") > -1)
{
requestConfig.httpsAgent = https.globalAgent;
}
else
{
requestConfig.httpAgent = http.globalAgent;
}
*/
return axios.request(requestConfig).then(function(response) {
callback(null, response, response.data);
}, function(error) {
callback(error);
});
};