| 3 | import { json } from "./json"; |
| 4 | |
| 5 | export async function applyRateLimit( |
| 6 | request: Request, |
| 7 | env: Env, |
| 8 | fn: () => Promise<Response> |
| 9 | ): Promise<Response> { |
| 10 | const apiKey = getApiKeyFromRequest(request); |
| 11 | if (apiKey) { |
| 12 | const result = await env.API_RATE_LIMITER.limit({ key: `apikey-${apiKey.apiKey}` }); |
| 13 | const { success } = result; |
| 14 | console.log(`Rate limiter`, { |
| 15 | success, |
| 16 | key: `${apiKey.apiKey.substring(0, 12)}...`, |
| 17 | }); |
| 18 | if (!success) { |
| 19 | //60s in the future |
| 20 | const reset = Date.now() + 60 * 1000; |
| 21 | const secondsUntilReset = Math.max(0, (reset - new Date().getTime()) / 1000); |
| 22 | |
| 23 | return json( |
| 24 | { |
| 25 | title: "Rate Limit Exceeded", |
| 26 | status: 429, |
| 27 | type: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429", |
| 28 | detail: `Rate limit exceeded. Retry in ${secondsUntilReset} seconds.`, |
| 29 | error: `Rate limit exceeded. Retry in ${secondsUntilReset} seconds.`, |
| 30 | reset, |
| 31 | }, |
| 32 | { |
| 33 | status: 429, |
| 34 | headers: { |
| 35 | "x-ratelimit-reset": reset.toString(), |
| 36 | }, |
| 37 | } |
| 38 | ); |
| 39 | } |
| 40 | } else { |
| 41 | console.log(`Rate limiter: no API key for request`); |
| 42 | } |
| 43 | |
| 44 | //call the original function |
| 45 | return fn(); |
| 46 | } |