| 1 | import type { MiddlewareHandler } from "hono"; |
| 2 | import type { AppEnv } from "../env"; |
| 3 | import { ApiError } from "./errors"; |
| 4 | |
| 5 | // Per-IP throttle for write endpoints. The binding may be absent under local |
| 6 | // `wrangler dev`, in which case the limiter is simply skipped. |
| 7 | export const writeRateLimit: MiddlewareHandler<AppEnv> = async (c, next) => { |
| 8 | const limiter = c.env.WRITE_LIMITER; |
| 9 | if (limiter) { |
| 10 | const ip = c.req.header("cf-connecting-ip") ?? "unknown"; |
| 11 | const { success } = await limiter.limit({ key: ip }); |
| 12 | if (!success) { |
| 13 | throw new ApiError(429, "rate_limited", "Too many requests. Please wait a minute and try again."); |
| 14 | } |
| 15 | } |
| 16 | await next(); |
| 17 | }; |
| 18 |