* feat: Put request rate limit at application server This PR contains implementation for a blanket rate limiter at application server level. Currently the allowed throughput is set high only to be changed later as per the actual data gathered. * Simplify implementation 1. Remove shutdown handler to purge rate limiter keys 2. Have separate keys for default and custom(route-based) rate limiters 3. Do not kill default rate limiter because it is not needed anymore due to (2) above * Set 60s as default for rate limiting window * Fix env types
34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
import { RateLimiterRedis } from "rate-limiter-flexible";
|
|
import env from "@server/env";
|
|
import Redis from "@server/redis";
|
|
import { RateLimiterConfig } from "@server/types";
|
|
|
|
export default class RateLimiter {
|
|
constructor() {
|
|
throw Error(`Cannot instantiate class!`);
|
|
}
|
|
|
|
static readonly RATE_LIMITER_REDIS_KEY_PREFIX = "rl";
|
|
|
|
static readonly rateLimiterMap = new Map<string, RateLimiterRedis>();
|
|
static readonly defaultRateLimiter = new RateLimiterRedis({
|
|
storeClient: Redis.defaultClient,
|
|
points: env.RATE_LIMITER_REQUESTS,
|
|
duration: env.RATE_LIMITER_DURATION_WINDOW,
|
|
keyPrefix: this.RATE_LIMITER_REDIS_KEY_PREFIX,
|
|
});
|
|
|
|
static getRateLimiter(path: string): RateLimiterRedis {
|
|
return this.rateLimiterMap.get(path) || this.defaultRateLimiter;
|
|
}
|
|
|
|
static setRateLimiter(path: string, config: RateLimiterConfig): void {
|
|
const rateLimiter = new RateLimiterRedis(config);
|
|
this.rateLimiterMap.set(path, rateLimiter);
|
|
}
|
|
|
|
static hasRateLimiter(path: string): boolean {
|
|
return this.rateLimiterMap.has(path);
|
|
}
|
|
}
|