-
-
Notifications
You must be signed in to change notification settings - Fork 57
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: fork ratelimit to log instead of blocking wih 429
- Loading branch information
1 parent
c83b19c
commit 0c3ea69
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import type { Context, Next } from '@hono/hono' | ||
import { createMiddleware } from 'hono/factory' | ||
|
||
const RATE_LIMIT_CONTEXT_KEY = '.rateLimited' | ||
// const STATUS_TOO_MANY_REQUESTS = 429 | ||
|
||
export interface RateLimitBinding { | ||
limit: LimitFunc | ||
} | ||
|
||
export interface LimitFunc { | ||
(options: LimitOptions): Promise<RateLimitResult> | ||
} | ||
|
||
interface RateLimitResult { | ||
success: boolean | ||
} | ||
|
||
export interface LimitOptions { | ||
key: string | ||
} | ||
|
||
export interface RateLimitResponse { | ||
key: string | ||
success: boolean | ||
} | ||
|
||
export interface RateLimitOptions { | ||
continueOnRateLimit: boolean | ||
} | ||
|
||
export interface RateLimitKeyFunc { | ||
(c: Context): string | ||
} | ||
|
||
export function rateLimit(rateLimitBinding: RateLimitBinding, keyFunc: RateLimitKeyFunc, rateLimit: string = '') { | ||
return createMiddleware(async (c: Context, next: Next) => { | ||
const key = keyFunc(c) | ||
if (!key) { | ||
console.warn('the provided keyFunc returned an empty rate limiting key: bypassing rate limits') | ||
} | ||
if (key) { | ||
const { success } = await rateLimitBinding.limit({ key }) | ||
c.set(RATE_LIMIT_CONTEXT_KEY, success) | ||
|
||
if (!success) { | ||
// throw new HTTPException(STATUS_TOO_MANY_REQUESTS, { | ||
// res: c.text("rate limited", { status: STATUS_TOO_MANY_REQUESTS }), | ||
// }); | ||
console.warn(`The rate limit has been reached for key: ${key} and rate limit binding: ${rateLimit}`) | ||
} | ||
} | ||
|
||
// Call the next handler/middleware in the stack on success | ||
await next() | ||
}) | ||
} | ||
|
||
export function wasRateLimited(c: Context): boolean { | ||
return c.get(RATE_LIMIT_CONTEXT_KEY) as boolean | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters