Explorar el Código

refactor reg exp

yuken hace 3 años
padre
commit
ebf1267a2e
Se han modificado 1 ficheros con 11 adiciones y 7 borrados
  1. 11 7
      packages/app/src/server/middlewares/api-rate-limiter.ts

+ 11 - 7
packages/app/src/server/middlewares/api-rate-limiter.ts

@@ -29,6 +29,7 @@ const rateLimiter = new RateLimiterMongo(opts);
 const apiRateLimitConfigWithoutRegExp = generateApiRateLimitConfig(false);
 const apiRateLimitConfigWithRegExp = generateApiRateLimitConfig(true);
 const keysWithRegExp = Object.keys(apiRateLimitConfigWithRegExp).map(key => new RegExp(key));
+const valuesWithRegExp = Object.values(apiRateLimitConfigWithRegExp);
 
 const consumePoints = async(rateLimiter: RateLimiterMongo, key: string, points: number) => {
   const consumePoints = defaultMaxPoints / points;
@@ -43,13 +44,16 @@ module.exports = () => {
     const key = md5(req.ip + endpoint);
 
     let customizedConfig;
-    keysWithRegExp.forEach((key) => {
-      if (key.test(endpoint)) {
-        customizedConfig = apiRateLimitConfigWithRegExp[key.toString()];
-      }
-    });
-
-    customizedConfig = apiRateLimitConfigWithoutRegExp[endpoint];
+    if (keysWithRegExp.some(key => key.test(endpoint))) {
+      keysWithRegExp.forEach((key, index) => {
+        if (key.test(endpoint)) {
+          customizedConfig = valuesWithRegExp[index];
+        }
+      });
+    }
+    else {
+      customizedConfig = apiRateLimitConfigWithoutRegExp[endpoint];
+    }
 
     try {
       if (customizedConfig === undefined) {