From 28c8d318e11484dca1c6b2b67d0c5d14fa78fbf6 Mon Sep 17 00:00:00 2001 From: anatawa12 Date: Fri, 14 Jun 2024 17:18:33 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20long=20term=20/=20short=20term=20limit?= =?UTF-8?q?=E3=81=8C=E3=81=AA=E3=81=84=E3=81=A8=E3=81=8D=E3=81=A7=E3=82=82?= =?UTF-8?q?=E3=81=9D=E3=82=8C=E3=81=9E=E3=82=8C=E7=94=A8=E3=81=AEnew=20Lim?= =?UTF-8?q?iter=E3=81=A8limiter.get=E3=81=8C=E5=91=BC=E3=81=B0=E3=82=8C?= =?UTF-8?q?=E3=82=8B=E5=95=8F=E9=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/server/api/RateLimiterService.ts | 42 ++++++++++--------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/packages/backend/src/server/api/RateLimiterService.ts b/packages/backend/src/server/api/RateLimiterService.ts index 52d73baa0a..c212c0fa45 100644 --- a/packages/backend/src/server/api/RateLimiterService.ts +++ b/packages/backend/src/server/api/RateLimiterService.ts @@ -32,13 +32,13 @@ export class RateLimiterService { @bindThis public limit(limitation: IEndpointMeta['limit'] & { key: NonNullable }, actor: string, factor = 1) { - { - if (this.disabled) { - return Promise.resolve(); - } + if (this.disabled) { + return Promise.resolve(); + } - // Short-term limit - const min = new Promise((ok, reject) => { + // Short-term limit + const min = () => { + return new Promise((ok, reject) => { const minIntervalLimiter = new Limiter({ id: `${actor}:${limitation.key}:min`, duration: limitation.minInterval! * factor, @@ -57,16 +57,18 @@ export class RateLimiterService { return reject({ code: 'BRIEF_REQUEST_INTERVAL', info }); } else { if (hasLongTermLimit) { - return max.then(ok, reject); + return max().then(ok, reject); } else { return ok(); } } }); }); + }; - // Long term limit - const max = new Promise((ok, reject) => { + // Long term limit + const max = () => { + return new Promise((ok, reject) => { const limiter = new Limiter({ id: `${actor}:${limitation.key}`, duration: limitation.duration! * factor, @@ -88,20 +90,20 @@ export class RateLimiterService { } }); }); + }; - const hasShortTermLimit = typeof limitation.minInterval === 'number'; + const hasShortTermLimit = typeof limitation.minInterval === 'number'; - const hasLongTermLimit = - typeof limitation.duration === 'number' && - typeof limitation.max === 'number'; + const hasLongTermLimit = + typeof limitation.duration === 'number' && + typeof limitation.max === 'number'; - if (hasShortTermLimit) { - return min; - } else if (hasLongTermLimit) { - return max; - } else { - return Promise.resolve(); - } + if (hasShortTermLimit) { + return min(); + } else if (hasLongTermLimit) { + return max(); + } else { + return Promise.resolve(); } } }