(req: IncomingMessage)
| 112 | * @throws {ApiError} `bad-request` for a body that is too large or is not JSON. |
| 113 | */ |
| 114 | export async function readJsonBody(req: IncomingMessage): Promise<unknown> { |
| 115 | const chunks: Buffer[] = []; |
| 116 | let size = 0; |
| 117 | try { |
| 118 | for await (const chunk of req) { |
| 119 | const buf = chunk as Buffer; |
| 120 | size += buf.length; |
| 121 | if (size > MAX_BODY_BYTES) { |
| 122 | req.destroy(); |
| 123 | throw badRequest(`That request body is too large (max ${MAX_BODY_BYTES} bytes).`); |
| 124 | } |
| 125 | chunks.push(buf); |
| 126 | } |
| 127 | } catch (err) { |
| 128 | if (err instanceof ApiError) throw err; |
| 129 | throw badRequest('That request body could not be read.'); |
| 130 | } |
| 131 | if (size === 0) throw badRequest('That request needs a JSON body.'); |
| 132 | try { |
| 133 | return JSON.parse(Buffer.concat(chunks).toString('utf-8')) as unknown; |
| 134 | } catch { |
| 135 | throw badRequest('That request body is not valid JSON.'); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // ============================================================================= |
| 140 | // Query parameters |
no test coverage detected