Skip to content

Commit

Permalink
remove most instances of 'self' in favor of arrow functions (#634)
Browse files Browse the repository at this point in the history
why hello there temporal dead zone

Better way of defining args

Removed last bastion of self
  • Loading branch information
paulasjes-stripe authored and rattrayalex-stripe committed Jun 5, 2019
1 parent 4eb6918 commit e542902
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 85 deletions.
11 changes: 4 additions & 7 deletions lib/StripeMethod.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,21 @@ const makeAutoPaginationMethods = require('./autoPagination')
* @param [spec.host] Hostname for the request.
*/
function stripeMethod(spec) {
return function() {
const self = this;
const args = [].slice.call(arguments);

return function(...args) {
const callback = typeof args[args.length - 1] == 'function' && args.pop();

spec.urlParams = utils.extractUrlParams(
self.createResourcePathWithSymbols(spec.path || '')
this.createResourcePathWithSymbols(spec.path || '')
);

const requestPromise = utils.callbackifyPromiseWithTimeout(
makeRequest(self, args, spec, {}),
makeRequest(this, args, spec, {}),
callback
);

if (spec.methodType === 'list') {
const autoPaginationMethods = makeAutoPaginationMethods(
self,
this,
args,
spec,
requestPromise
Expand Down
144 changes: 70 additions & 74 deletions lib/StripeResource.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ StripeResource.prototype = {
wrapTimeout: utils.callbackifyPromiseWithTimeout,

_timeoutHandler(timeout, req, callback) {
const self = this;
return () => {
const timeoutErr = new Error('ETIMEDOUT');
timeoutErr.code = 'ETIMEDOUT';
Expand All @@ -96,7 +95,7 @@ StripeResource.prototype = {
req.abort();

callback.call(
self,
this,
new Error.StripeConnectionError({
message: `Request aborted due to timeout being reached (${timeout}ms)`,
detail: timeoutErr,
Expand All @@ -107,7 +106,6 @@ StripeResource.prototype = {
},

_responseHandler(req, callback) {
const self = this;
return (res) => {
let response = '';

Expand Down Expand Up @@ -136,7 +134,7 @@ StripeResource.prototype = {
elapsed: requestDurationMs,
});

self._stripe._emitter.emit('response', responseEvent);
this._stripe._emitter.emit('response', responseEvent);

try {
response = JSON.parse(response);
Expand Down Expand Up @@ -166,11 +164,11 @@ StripeResource.prototype = {
} else {
err = Error.StripeError.generate(response.error);
}
return callback.call(self, err, null);
return callback.call(this, err, null);
}
} catch (e) {
return callback.call(
self,
this,
new Error.StripeAPIError({
message: 'Invalid JSON received from the Stripe API',
response,
Expand All @@ -181,15 +179,15 @@ StripeResource.prototype = {
);
}

self._recordRequestMetrics(res.requestId, requestDurationMs);
this._recordRequestMetrics(res.requestId, requestDurationMs);

// Expose res object
Object.defineProperty(response, 'lastResponse', {
enumerable: false,
writable: false,
value: res,
});
callback.call(self, null, response);
callback.call(this, null, response);
});
};
},
Expand All @@ -201,16 +199,15 @@ StripeResource.prototype = {
},

_errorHandler(req, requestRetries, callback) {
const self = this;
return (error) => {
if (req._isAborted) {
// already handled
return;
}
callback.call(
self,
this,
new Error.StripeConnectionError({
message: self._generateConnectionErrorMessage(requestRetries),
message: this._generateConnectionErrorMessage(requestRetries),
detail: error,
}),
null
Expand Down Expand Up @@ -321,70 +318,20 @@ StripeResource.prototype = {
},

_request(method, host, path, data, auth, options, callback) {
const self = this;
let requestData;

function makeRequestWithData(error, data) {
if (error) {
return callback(error);
}

const apiVersion = self._stripe.getApiField('version');
requestData = data;
const headers = self._defaultHeaders(
auth,
requestData.length,
apiVersion
);

self._stripe.getClientUserAgent((cua) => {
headers['X-Stripe-Client-User-Agent'] = cua;

if (options.headers) {
Object.assign(headers, options.headers);
}

self._addTelemetryHeader(headers);

makeRequest(apiVersion, headers);
});
}

if (self.requestDataProcessor) {
self.requestDataProcessor(
method,
data,
options.headers,
makeRequestWithData
);
} else {
makeRequestWithData(null, utils.stringifyRequestData(data || {}));
}

function retryRequest(requestFn, apiVersion, headers, requestRetries) {
requestRetries += 1;

return setTimeout(
requestFn,
self._getSleepTimeInMS(requestRetries),
apiVersion,
headers,
requestRetries
);
}

function makeRequest(apiVersion, headers, numRetries) {
const timeout = self._stripe.getApiField('timeout');
const makeRequest = (apiVersion, headers, numRetries) => {
const timeout = this._stripe.getApiField('timeout');
const isInsecureConnection =
self._stripe.getApiField('protocol') == 'http';
let agent = self._stripe.getApiField('agent');
this._stripe.getApiField('protocol') == 'http';
let agent = this._stripe.getApiField('agent');
if (agent == null) {
agent = isInsecureConnection ? defaultHttpAgent : defaultHttpsAgent;
}

const req = (isInsecureConnection ? http : https).request({
host: host || self._stripe.getApiField('host'),
port: self._stripe.getApiField('port'),
host: host || this._stripe.getApiField('host'),
port: this._stripe.getApiField('port'),
path,
method,
agent,
Expand All @@ -394,7 +341,7 @@ StripeResource.prototype = {

// If this is a POST and we allow multiple retries, set a idempotency key if one is not
// already provided.
if (method === 'POST' && self._stripe.getMaxNetworkRetries() > 0) {
if (method === 'POST' && this._stripe.getMaxNetworkRetries() > 0) {
if (!headers.hasOwnProperty('Idempotency-Key')) {
headers['Idempotency-Key'] = uuid();
}
Expand All @@ -414,23 +361,23 @@ StripeResource.prototype = {

req._requestStart = Date.now();

self._stripe._emitter.emit('request', requestEvent);
this._stripe._emitter.emit('request', requestEvent);

req.setTimeout(timeout, self._timeoutHandler(timeout, req, callback));
req.setTimeout(timeout, this._timeoutHandler(timeout, req, callback));

req.on('response', (res) => {
if (self._shouldRetry(res, requestRetries)) {
if (this._shouldRetry(res, requestRetries)) {
return retryRequest(makeRequest, apiVersion, headers, requestRetries);
} else {
return self._responseHandler(req, callback)(res);
return this._responseHandler(req, callback)(res);
}
});

req.on('error', (error) => {
if (self._shouldRetry(null, requestRetries)) {
if (this._shouldRetry(null, requestRetries)) {
return retryRequest(makeRequest, apiVersion, headers, requestRetries);
} else {
return self._errorHandler(req, requestRetries, callback)(error);
return this._errorHandler(req, requestRetries, callback)(error);
}
});

Expand All @@ -447,7 +394,56 @@ StripeResource.prototype = {
req.end();
}
});
};

const makeRequestWithData = (error, data) => {
if (error) {
return callback(error);
}

const apiVersion = this._stripe.getApiField('version');
requestData = data;
const headers = this._defaultHeaders(
auth,
requestData.length,
apiVersion
);

this._stripe.getClientUserAgent((cua) => {
headers['X-Stripe-Client-User-Agent'] = cua;

if (options.headers) {
Object.assign(headers, options.headers);
}

this._addTelemetryHeader(headers);

makeRequest(apiVersion, headers);
});
};

if (this.requestDataProcessor) {
this.requestDataProcessor(
method,
data,
options.headers,
makeRequestWithData
);
} else {
makeRequestWithData(null, utils.stringifyRequestData(data || {}));
}

const retryRequest = (requestFn, apiVersion, headers, requestRetries) => {
requestRetries += 1;

return setTimeout(
requestFn,
this._getSleepTimeInMS(requestRetries),
apiVersion,
headers,
requestRetries
);
};
},
};

Expand Down
6 changes: 2 additions & 4 deletions lib/stripe.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,6 @@ Stripe.prototype = {
// Gets a JSON version of a User-Agent by encoding a seeded object and
// fetching a uname from the system.
getClientUserAgentSeeded(seed, cb) {
const self = this;

utils.safeExec('uname -a', (err, uname) => {
const userAgent = {};
for (const field in seed) {
Expand All @@ -213,8 +211,8 @@ Stripe.prototype = {
// URI-encode in case there are unusual characters in the system's uname.
userAgent.uname = encodeURIComponent(uname || 'UNKNOWN');

if (self._appInfo) {
userAgent.application = self._appInfo;
if (this._appInfo) {
userAgent.application = this._appInfo;
}

cb(JSON.stringify(userAgent));
Expand Down

0 comments on commit e542902

Please sign in to comment.