Handle errors from redis store in request rate limit

This commit is contained in:
Ajay
2022-09-22 11:12:47 -04:00
parent 30bac658ed
commit 7007ab05e1

View File

@@ -1,9 +1,9 @@
import { getIP } from "../utils/getIP"; import { getIP } from "../utils/getIP";
import { getHash } from "../utils/getHash"; import { getHash } from "../utils/getHash";
import { getHashCache } from "../utils/getHashCache"; import { getHashCache } from "../utils/getHashCache";
import rateLimit, { RateLimitRequestHandler } from "express-rate-limit"; import rateLimit from "express-rate-limit";
import { RateLimitConfig } from "../types/config.model"; import { RateLimitConfig } from "../types/config.model";
import { Request } from "express"; import { Request, RequestHandler } from "express";
import { isUserVIP } from "../utils/isUserVIP"; import { isUserVIP } from "../utils/isUserVIP";
import { UserID } from "../types/user.model"; import { UserID } from "../types/user.model";
import RedisStore, { RedisReply } from "rate-limit-redis"; import RedisStore, { RedisReply } from "rate-limit-redis";
@@ -11,7 +11,8 @@ import redis from "../utils/redis";
import { config } from "../config"; import { config } from "../config";
import { Logger } from "../utils/logger"; import { Logger } from "../utils/logger";
export function rateLimitMiddleware(limitConfig: RateLimitConfig, getUserID?: (req: Request) => UserID): RateLimitRequestHandler { export function rateLimitMiddleware(limitConfig: RateLimitConfig, getUserID?: (req: Request) => UserID): RequestHandler {
try {
return rateLimit({ return rateLimit({
windowMs: limitConfig.windowMs, windowMs: limitConfig.windowMs,
max: limitConfig.max, max: limitConfig.max,
@@ -34,4 +35,8 @@ export function rateLimitMiddleware(limitConfig: RateLimitConfig, getUserID?: (r
sendCommand: (...args: string[]) => redis.sendCommand(args).catch((err) => Logger.error(err)) as Promise<RedisReply>, sendCommand: (...args: string[]) => redis.sendCommand(args).catch((err) => Logger.error(err)) as Promise<RedisReply>,
}) : null, }) : null,
}); });
} catch (e) {
Logger.error(`Rate limit error: ${e}`);
return (req, res, next) => next();
}
} }