| 1 | import { BodyReadError, readBoundedBody } from "./bounded-body"; |
| 2 | |
| 3 | export class FormBodyError extends Error { |
| 4 | constructor( |
| 5 | readonly status: 400 | 413 | 415, |
| 6 | message: string |
| 7 | ) { |
| 8 | super(message); |
| 9 | this.name = "FormBodyError"; |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | export async function readBoundedUrlEncodedForm( |
| 14 | request: Request, |
| 15 | maxBytes: number |
| 16 | ): Promise<URLSearchParams> { |
| 17 | const mediaType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase(); |
| 18 | if (mediaType !== "application/x-www-form-urlencoded") { |
| 19 | throw new FormBodyError(415, "expected application/x-www-form-urlencoded"); |
| 20 | } |
| 21 | |
| 22 | try { |
| 23 | const bytes = await readBoundedBody(request, maxBytes); |
| 24 | return new URLSearchParams(new TextDecoder().decode(bytes)); |
| 25 | } catch (cause) { |
| 26 | if (cause instanceof BodyReadError) throw new FormBodyError(cause.status, cause.message); |
| 27 | throw cause; |
| 28 | } |
| 29 | } |
| 30 |