From d8e38354068c18a90197a84f282dafda8c81f17d Mon Sep 17 00:00:00 2001 From: Bajarang Agarwal Date: Sun, 24 Sep 2017 15:00:34 +0530 Subject: [PATCH] Supporting of returning remaining rate limit information --- lib/transport.js | 78 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/lib/transport.js b/lib/transport.js index 07ef4b5..2196ee4 100644 --- a/lib/transport.js +++ b/lib/transport.js @@ -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; }, @@ -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;