소스 검색

refactor middleware

yuken 3 년 전
부모
커밋
ee1823cdcd
1개의 변경된 파일19개의 추가작업 그리고 17개의 파일을 삭제
  1. 19 17
      packages/app/src/server/middlewares/api-rate-limiter.ts

+ 19 - 17
packages/app/src/server/middlewares/api-rate-limiter.ts

@@ -27,15 +27,9 @@ const rateLimiter = new RateLimiterMongo(opts);
 // generate ApiRateLimitConfig for api rate limiter
 const apiRateLimitConfig = generateApiRateLimitConfig();
 
-const consumePoints = async(rateLimiter: RateLimiterMongo, key: string, points: number, next: NextFunction) => {
+const consumePoints = async(rateLimiter: RateLimiterMongo, key: string, points: number) => {
   const consumePoints = defaultMaxPoints / points;
-  try {
-    await rateLimiter.consume(key, consumePoints);
-    next();
-  }
-  catch {
-    logger.error(`too many request at ${key}`);
-  }
+  await rateLimiter.consume(key, consumePoints);
 };
 
 module.exports = () => {
@@ -47,17 +41,25 @@ module.exports = () => {
 
     const customizedConfig = apiRateLimitConfig[endpoint];
 
-    if (customizedConfig === undefined) {
-      await consumePoints(rateLimiter, key, defaultMaxRequests, next);
-      return;
-    }
+    try {
+      if (customizedConfig === undefined) {
+        await consumePoints(rateLimiter, key, defaultMaxRequests);
+        next();
+        return;
+      }
+
+      if (customizedConfig.method.includes(req.method) || customizedConfig.method === 'ALL') {
+        await consumePoints(rateLimiter, key, customizedConfig.maxRequests);
+        next();
+        return;
+      }
 
-    if (customizedConfig.method.includes(req.method) || customizedConfig.method === 'ALL') {
-      await consumePoints(rateLimiter, key, customizedConfig.maxRequests, next);
+      await consumePoints(rateLimiter, key, defaultMaxRequests);
+      next();
       return;
     }
-
-    await consumePoints(rateLimiter, key, defaultMaxRequests, next);
-    return;
+    catch {
+      logger.error(`too many request at ${key}`);
+    }
   };
 };