Skip to content
This repository has been archived by the owner on Jul 19, 2022. It is now read-only.

Supporting of returning remaining rate limit information #54

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions lib/transport.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,37 @@ module.exports = {
}
},

_onResponseFetchLimit: function(options, err, res) {
if (res && res.ok === true && !err) {
options.resolve(res.header['x-rate-limit-remaining']);
} else {
var isStatus401 = res && res.status === 401;
var isInvalidOrExpiredToken = (res.body.error === 'invalid_token' || res.body.error_description === 'expired_token');
var hasRefreshToken = this.authObject && this.authObject.refreshToken;

if (isStatus401 && isInvalidOrExpiredToken && hasRefreshToken) {

this._getAuth()._refreshToken(function (err, response) {
if (err !== null) {
options.reject(this._handleTransportError(options, response));
}

if (_.isFunction(this.afterTokenRefreshed)) {
this.afterTokenRefreshed(response);
}

this._onTokenRefreshed(options.requestParams).then(function (response) {
options.resolve(response);
}, function (err) {
options.reject(err);
})
}.bind(this));
} else {
options.reject(this._handleTransportError(options, res));
}
}
},

_getRequestObject: function() {
return request;
},
Expand Down Expand Up @@ -207,6 +238,53 @@ module.exports = {
}.bind(this));
},

getRateLimit: function(method, path, data, options){

var url = this._getRequestURI(path);
var request = this._getRequestObject();
var req;

if ((!options || !options.basicAuth) && !this.authObject) {
return new Promise(function (resolve, reject) {
reject(new PodioErrors.PodioForbiddenError('Authentication has not been performed'))
});
}

method = this._formatMethod(method);

req = request[method](url);

if (options && options.basicAuth) {
req = _.compose(
this._addRequestData.bind(this, data, method),
this._setOptions.bind(this, options || {})
)(req);
} else {
req = _.compose(
this._addRequestData.bind(this, data, method),
this._addHeaders.bind(this),
this._addCORS.bind(this),
this._setOptions.bind(this, options || {})
)(req);
}

return new Promise(function(resolve, reject) {
var options = {
resolve: resolve,
reject: reject,
requestParams: {
requestType: 'generic',
url: url,
path: path,
data: data,
method: method
}
};

req.end(this._onResponseFetchLimit.bind(this, options));
}.bind(this));
},

uploadFile: function(filePath, fileName) {
var url = new URI(this.apiURL).path('/file').toString();
var req;
Expand Down