Comply to the new Rate Limit Headers hammerandchisel/discord-api-docs#108

This commit is contained in:
Amish Shah
2016-08-19 19:03:06 +01:00
parent c2e3d2b8ca
commit 75ff9fb096
3 changed files with 21 additions and 3 deletions

View File

@@ -12,6 +12,7 @@ class RESTManager {
this.userAgentManager = new UserAgentManager(this);
this.methods = new RESTMethods(this);
this.rateLimitedEndpoints = {};
this.globallyRateLimited = false;
}
push(handler, apiRequest) {

View File

@@ -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

View File

@@ -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'];
@@ -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;
@@ -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) {
@@ -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;