From cd54e9317ff0396a34bafacce2ff2c056a4b0cee Mon Sep 17 00:00:00 2001 From: Gus Caplan Date: Fri, 27 Oct 2017 08:36:53 -0500 Subject: [PATCH] Time Difference in REST (#2057) --- src/rest/RESTManager.js | 10 ++++++++++ src/rest/handlers/RequestHandler.js | 7 +++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/rest/RESTManager.js b/src/rest/RESTManager.js index 48476cca6..d62423979 100644 --- a/src/rest/RESTManager.js +++ b/src/rest/RESTManager.js @@ -12,12 +12,22 @@ class RESTManager { this.globallyRateLimited = false; this.tokenPrefix = tokenPrefix; this.versioned = true; + this.timeDifferences = []; } get api() { return routeBuilder(this); } + get timeDifference() { + return Math.round(this.timeDifferences.reduce((a, b) => a + b, 0) / this.timeDifferences.length); + } + + set timeDifference(ms) { + this.timeDifferences.unshift(ms); + if (this.timeDifferences.length > 5) this.timeDifferences.length = 5; + } + getAuth() { const token = this.client.token || this.client.accessToken; const prefixed = !!this.client.application || (this.client.user && this.client.user.bot); diff --git a/src/rest/handlers/RequestHandler.js b/src/rest/handlers/RequestHandler.js index aaeed9d69..64e9ea72b 100644 --- a/src/rest/handlers/RequestHandler.js +++ b/src/rest/handlers/RequestHandler.js @@ -9,7 +9,6 @@ class RequestHandler { this.limit = Infinity; this.resetTime = null; this.remaining = 1; - this.timeDifference = 0; this.queue = []; } @@ -32,7 +31,7 @@ class RequestHandler { const finish = timeout => { if (timeout || this.limited) { if (!timeout) { - timeout = this.resetTime - Date.now() + this.timeDifference + this.client.options.restTimeOffset; + timeout = this.resetTime - Date.now() + this.manager.timeDifference + this.client.options.restTimeOffset; } // eslint-disable-next-line prefer-promise-reject-errors reject({ timeout }); @@ -50,7 +49,7 @@ class RequestHandler { this.client.emit(RATE_LIMIT, { timeout, limit: this.limit, - timeDifference: this.timeDifference, + timeDifference: this.manager.timeDifference, method: item.request.method, path: item.request.path, route: item.request.route, @@ -66,7 +65,7 @@ class RequestHandler { this.limit = Number(res.headers['x-ratelimit-limit']); this.resetTime = Number(res.headers['x-ratelimit-reset']) * 1000; this.remaining = Number(res.headers['x-ratelimit-remaining']); - this.timeDifference = Date.now() - new Date(res.headers.date).getTime(); + this.manager.timeDifference = Date.now() - new Date(res.headers.date).getTime(); } if (err) { if (err.status === 429) {