Skip to content

Commit

Permalink
Comply to the new Rate Limit Headers discord/discord-api-docs#108
Browse files Browse the repository at this point in the history
  • Loading branch information
amishshah committed Aug 19, 2016
1 parent c2e3d2b commit 75ff9fb
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/client/rest/RESTManager.js
Expand Up @@ -12,6 +12,7 @@ class RESTManager {
this.userAgentManager = new UserAgentManager(this);
this.methods = new RESTMethods(this);
this.rateLimitedEndpoints = {};
this.globallyRateLimited = false;
}

push(handler, apiRequest) {
Expand Down
12 changes: 12 additions & 0 deletions src/client/rest/RequestHandlers/RequestHandler.js
Expand Up @@ -17,6 +17,18 @@ module.exports = class RequestHandler {
this.queue = [];
}

/**
* Whether or not the client is being rate limited on every endpoint.
* @type {Boolean}
*/
get globalLimit() {
return this.restManager.globallyRateLimited;
}

set globalLimit(value) {
this.restManager.globallyRateLimited = value;
}

/**
* Push a new API request into this bucket
* @param {APIRequest} request the new request to push into the queue
Expand Down
11 changes: 8 additions & 3 deletions src/client/rest/RequestHandlers/Sequential.js
Expand Up @@ -36,7 +36,7 @@ module.exports = class SequentialRequestHandler extends RequestHandler {
* @returns {Promise<Object, Error>}
*/
execute(item) {
return new Promise((resolve, reject) => {
return new Promise(resolve => {
item.request.gen().end((err, res) => {
if (res && res.headers) {
this.requestLimit = res.headers['x-ratelimit-limit'];
Expand All @@ -48,8 +48,12 @@ module.exports = class SequentialRequestHandler extends RequestHandler {
if (err.status === 429) {
setTimeout(() => {
this.waiting = false;
this.globalLimit = false;
resolve();
}, res.headers['retry-after']);
}, res.headers['retry-after'] + 500);
if (res.headers['x-ratelimit-global']) {
this.globalLimit = true;
}
} else {
this.queue.shift();
this.waiting = false;
Expand All @@ -58,6 +62,7 @@ module.exports = class SequentialRequestHandler extends RequestHandler {
}
} else {
this.queue.shift();
this.globalLimit = false;
const data = res && res.body ? res.body : {};
item.resolve(data);
if (this.requestRemaining === 0) {
Expand All @@ -76,7 +81,7 @@ module.exports = class SequentialRequestHandler extends RequestHandler {

handle() {
super.handle();
if (this.waiting || this.queue.length === 0) {
if (this.waiting || this.queue.length === 0 || this.globalLimit) {
return;
}
this.waiting = true;
Expand Down

0 comments on commit 75ff9fb

Please sign in to comment.