(
res: NodeHttpResponse,
standardResponse: StandardResponse,
options: SendStandardResponseOptions = {},
)
| 7 | export interface SendStandardResponseOptions extends ToNodeHttpBodyOptions {} |
| 8 | |
| 9 | export function sendStandardResponse( |
| 10 | res: NodeHttpResponse, |
| 11 | standardResponse: StandardResponse, |
| 12 | options: SendStandardResponseOptions = {}, |
| 13 | ): Promise<void> { |
| 14 | return new Promise((resolve, reject) => { |
| 15 | res.once('error', reject) |
| 16 | res.once('close', resolve) |
| 17 | |
| 18 | const resHeaders: StandardHeaders = { ...standardResponse.headers } |
| 19 | |
| 20 | const resBody = toNodeHttpBody(standardResponse.body, resHeaders, options) |
| 21 | |
| 22 | // Node.js throws an error when a header is undefined, so remember to use toNodeHttpHeaders |
| 23 | // to filter out undefined headers |
| 24 | res.writeHead(standardResponse.status, toNodeHttpHeaders(resHeaders)) |
| 25 | |
| 26 | if (resBody === undefined) { |
| 27 | res.end() |
| 28 | } |
| 29 | else if (typeof resBody === 'string') { |
| 30 | res.end(resBody) |
| 31 | } |
| 32 | else { |
| 33 | res.once('close', () => { |
| 34 | if (!resBody.closed) { |
| 35 | resBody.destroy(res.errored ?? undefined) |
| 36 | } |
| 37 | }) |
| 38 | |
| 39 | resBody.once('error', error => res.destroy(error)) |
| 40 | |
| 41 | resBody.pipe(res) |
| 42 | } |
| 43 | }) |
| 44 | } |
no test coverage detected