Skip to content

Commit

Permalink
chore: migrate from deprecated request module to axios
Browse files Browse the repository at this point in the history
  • Loading branch information
eshanholtz committed Mar 6, 2020
1 parent 5249e3b commit d547d51
Show file tree
Hide file tree
Showing 4 changed files with 119 additions and 346 deletions.
44 changes: 25 additions & 19 deletions lib/base/RequestClient.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
'use strict';

var _ = require('lodash');
var http = require('request');
var axios = require('axios');
var fs = require('fs');
var http = require('http');
var https = require('https');
var Q = require('q');
var qs = require('qs');
var Response = require('../http/response');
var Request = require('../http/request');

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

var RequestClient = function() {};

/**
Expand Down Expand Up @@ -47,11 +52,12 @@ RequestClient.prototype.request = function(opts) {

var options = {
timeout: opts.timeout || 30000,
followRedirect: opts.allowRedirects || false,
maxRedirects: opts.allowRedirects ? 10 : 0, // Same number of allowed redirects as request module default
url: opts.uri,
method: opts.method,
headers: opts.headers,
forever: opts.forever === false ? false : true,
httpAgent: opts.forever ? new http.Agent({ keepAlive: true }) : undefined,
httpsAgent: opts.forever ? new https.Agent({ keepAlive: true }) : undefined,
};

if (process.env.TWILIO_CA_BUNDLE !== undefined) {
Expand All @@ -62,20 +68,22 @@ RequestClient.prototype.request = function(opts) {
}

if (!_.isNull(opts.data)) {
options.formData = opts.data;
options.data = qs.stringify(opts.data, { arrayFormat: 'repeat'});
}

if (!_.isNull(opts.params)) {
options.qs = opts.params;
options.useQuerystring = true;
options.params = opts.params;
options.paramSerializer = (params) => {
return qs.stringify(params, { arrayFormat: 'repeat' });
};
}

var optionsRequest = {
method: options.method,
url: options.url,
auth: b64Auth || null,
params: options.qs,
data: options.formData,
params: options.params,
data: opts.data,
headers: options.headers,
ca: options.ca
};
Expand All @@ -84,17 +92,15 @@ RequestClient.prototype.request = function(opts) {
this.lastResponse = undefined;
this.lastRequest = new Request(optionsRequest);

http(options, function(error, response) {
if (error) {
_this.lastResponse = undefined;
deferred.reject(error);
} else {
_this.lastResponse = new Response(response.statusCode, response.body);
deferred.resolve({
statusCode: response.statusCode,
body: response.body,
});
}
axios(options).then((response) => {
_this.lastResponse = new Response(response.status, response.data);
deferred.resolve({
statusCode: response.status,
body: response.data,
});
}).catch((error) => {
_this.lastResponse = undefined;
deferred.reject(error);
});

return deferred.promise;
Expand Down
Loading

0 comments on commit d547d51

Please sign in to comment.