( request: Request, maxBytes: number = DEFAULT_MAX_JSON_BODY_BYTES )
| 160 | * metadata on a deploy call) — `parseJsonBody` rejects empty bodies. |
| 161 | */ |
| 162 | export async function parseOptionalJsonBody( |
| 163 | request: Request, |
| 164 | maxBytes: number = DEFAULT_MAX_JSON_BODY_BYTES |
| 165 | ): Promise< |
| 166 | { success: true; data: unknown } | { success: false; response: NextResponse<{ error: string }> } |
| 167 | > { |
| 168 | try { |
| 169 | assertContentLengthWithinLimit(request.headers, maxBytes, REQUEST_BODY_LABEL) |
| 170 | |
| 171 | const stream = request.body |
| 172 | const text = stream |
| 173 | ? new TextDecoder().decode( |
| 174 | await readStreamToBufferWithLimit(stream, { maxBytes, label: REQUEST_BODY_LABEL }) |
| 175 | ) |
| 176 | : await request.text() |
| 177 | |
| 178 | if (!text.trim()) { |
| 179 | return { success: true, data: undefined } |
| 180 | } |
| 181 | return { success: true, data: JSON.parse(text) } |
| 182 | } catch (error) { |
| 183 | if (isPayloadSizeLimitError(error)) { |
| 184 | return { |
| 185 | success: false, |
| 186 | response: NextResponse.json( |
| 187 | { error: `Request body exceeds the maximum allowed size of ${maxBytes} bytes` }, |
| 188 | { status: 413 } |
| 189 | ), |
| 190 | } |
| 191 | } |
| 192 | return { |
| 193 | success: false, |
| 194 | response: NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }), |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | export function searchParamsToObject( |
| 200 | searchParams: URLSearchParams |
no test coverage detected