Skip to content

Commit

Permalink
Refactor rate limit middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
NeKzor committed Feb 8, 2025
1 parent cc7ef7b commit 0b787fa
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions src/server/rate_limits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,10 @@ import { RouterMiddleware, Status, STATUS_TEXT } from '@oak/oak';
import { RateLimiterAbstract, RateLimiterMemory, RateLimiterRes } from 'rate-limiter-flexible';
import { AppState } from './app/AppState.ts';

const buckets = {
authorize: new RateLimiterMemory({
points: 3,
duration: 60,
}),
views: new RateLimiterMemory({
points: 1,
duration: 30,
}),
};

// deno-lint-ignore no-explicit-any
type OakRouterMiddleware = RouterMiddleware<any, any, Record<string, any> & AppState>;

const tryConsume: (bucket: RateLimiterAbstract) => OakRouterMiddleware = (bucket) => async (ctx, next) => {
const rateLimitMiddleware: (bucket: RateLimiterAbstract) => OakRouterMiddleware = (bucket) => async (ctx, next) => {
let consumed = false;

try {
Expand All @@ -45,7 +34,17 @@ const tryConsume: (bucket: RateLimiterAbstract) => OakRouterMiddleware = (bucket
}
};

export const rateLimits: Record<keyof typeof buckets, OakRouterMiddleware> = {
authorize: tryConsume(buckets.authorize),
views: tryConsume(buckets.views),
};
export const rateLimits = {
authorize: rateLimitMiddleware(
new RateLimiterMemory({
points: 3,
duration: 60,
}),
),
views: rateLimitMiddleware(
new RateLimiterMemory({
points: 1,
duration: 30,
}),
),
} as const;

0 comments on commit 0b787fa

Please sign in to comment.