1+ var axios = require ( "axios" ) ;
2+
3+ // var http = require("http");
4+ // var https = require("https");
5+ //
6+ // var FormData = require("form-data");
7+
8+ /**
9+ * Incoming config:
10+ *
11+ * {
12+ * "url": "",
13+ * "method": "",
14+ * "headers": {},
15+ * "qs": {},
16+ * "data": "" | {},
17+ * "json": {}
18+ * }
19+ *
20+ * Callback is (err, response).
21+ *
22+ * Where response is the Axios response object.
23+ *
24+ * @param config
25+ * @param callback
26+ */
27+ module . exports = function ( config , callback )
28+ {
29+ // request config - https://github.com/request/request#requestoptions-callback
30+ // axios config - https://www.npmjs.com/package/axios
31+
32+ if ( ! callback ) {
33+ callback = function ( err , response , data ) {
34+ // nothing
35+ } ;
36+ }
37+
38+ var requestConfig = { } ;
39+ requestConfig . url = config . uri || config . url ;
40+ requestConfig . method = config . method || "get" ;
41+ requestConfig . headers = { } ;
42+
43+ if ( ! config ) {
44+ config = { } ;
45+ }
46+ if ( ! config . headers ) {
47+ config . headers = { } ;
48+ }
49+ for ( var k in config . headers )
50+ {
51+ var v = config . headers [ k ] ;
52+ if ( v )
53+ {
54+ requestConfig . headers [ k . trim ( ) . toLowerCase ( ) ] = v ;
55+ }
56+ }
57+ // support for FormData headers
58+ // copy form data headers
59+ if ( config . data && config . data . getHeaders )
60+ {
61+ var formDataHeaders = config . data . getHeaders ( ) ;
62+ for ( var k in formDataHeaders )
63+ {
64+ var v = formDataHeaders [ k ] ;
65+ requestConfig . headers [ k ] = v ;
66+ }
67+ }
68+
69+ if ( config . qs ) {
70+ requestConfig . params = config . qs ;
71+ }
72+
73+ if ( config . json ) {
74+ requestConfig . data = config . json ;
75+
76+ if ( ! requestConfig . headers [ "content-type" ] ) {
77+ requestConfig . headers [ "content-type" ] = "application/json" ;
78+ }
79+ }
80+
81+ if ( config . data )
82+ {
83+ requestConfig . data = config . data ;
84+
85+ if ( ! requestConfig . headers [ "content-type" ] )
86+ {
87+ if ( ! requestConfig . data )
88+ {
89+ if ( requestConfig . data . getHeaders )
90+ {
91+ // assume this is a FormData and skip
92+ }
93+ else if ( typeof ( requestConfig . data ) === "object" )
94+ {
95+ // send as json
96+ requestConfig . headers [ "content-type" ] = "application/json" ;
97+ }
98+ }
99+ }
100+ }
101+
102+ if ( config . responseType ) {
103+ requestConfig . responseType = config . responseType ;
104+ }
105+
106+
107+ /*
108+ if (requestConfig.url.toLowerCase().indexOf("https:") > -1)
109+ {
110+ requestConfig.httpsAgent = https.globalAgent;
111+ }
112+ else
113+ {
114+ requestConfig.httpAgent = http.globalAgent;
115+ }
116+ */
117+
118+ return axios . request ( requestConfig ) . then ( function ( response ) {
119+ callback ( null , response , response . data ) ;
120+ } , function ( error ) {
121+ callback ( error ) ;
122+ } ) ;
123+ } ;
0 commit comments