Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update errorResponseBuilderContext type with ban property #298

Merged
merged 5 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ declare module 'fastify' {
export interface FastifyRateLimitOptions {}

export interface errorResponseBuilderContext {
ban: boolean;
after: string;
max: number;
ttl: number;
Expand Down
16 changes: 15 additions & 1 deletion types/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,21 @@ const options1: RateLimitPluginOptions = {
errorResponseBuilder: (
req: FastifyRequest<RequestGenericInterface>,
context: errorResponseBuilderContext
) => ({ code: 429, timeWindow: context.after, limit: context.max }),
) => {
if (context.ban) {
return {
statusCode: 403,
error: "Forbidden",
message: `You can not access this service as you have sent too many requests that exceed your rate limit. Your IP: ${req.ip} and Limit: ${context.max}`,
}
} else {
return {
statusCode: 429,
error: "Too Many Requests",
message: `You hit the rate limit, please slow down! You can retry in ${context.after}`,
}
}
},
addHeadersOnExceeding: {
'x-ratelimit-limit': false,
'x-ratelimit-remaining': false,
Expand Down