( request: Request, invalidJson: ParseRequestOptions['invalidJson'] = 'response', maxBytes: number = DEFAULT_MAX_JSON_BODY_BYTES )
| 119 | } |
| 120 | |
| 121 | export async function parseJsonBody( |
| 122 | request: Request, |
| 123 | invalidJson: ParseRequestOptions['invalidJson'] = 'response', |
| 124 | maxBytes: number = DEFAULT_MAX_JSON_BODY_BYTES |
| 125 | ): Promise< |
| 126 | | { success: true; data: unknown } |
| 127 | | { |
| 128 | success: false |
| 129 | reason: 'too_large' | 'invalid_json' |
| 130 | response: NextResponse<{ error: string }> |
| 131 | } |
| 132 | > { |
| 133 | try { |
| 134 | return { success: true, data: await readJsonBodyWithLimit(request, maxBytes) } |
| 135 | } catch (error) { |
| 136 | if (invalidJson === 'throw') throw error |
| 137 | if (isPayloadSizeLimitError(error)) { |
| 138 | return { |
| 139 | success: false, |
| 140 | reason: 'too_large', |
| 141 | response: NextResponse.json( |
| 142 | { error: `Request body exceeds the maximum allowed size of ${maxBytes} bytes` }, |
| 143 | { status: 413 } |
| 144 | ), |
| 145 | } |
| 146 | } |
| 147 | return { |
| 148 | success: false, |
| 149 | reason: 'invalid_json', |
| 150 | response: NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }), |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /** |
| 156 | * Reads an entirely optional JSON body with the standard byte cap. An absent |
no test coverage detected