nest-koa-adapter
Version:
Koa HTTP adapter for Nest.js
62 lines • 2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.koaReply = void 0;
const stream_1 = require("stream");
function getOverwrites(response, statusCode) {
return {
status: response.status,
headers: Object.entries(response.headers),
};
}
function applyOverwrites(response, overwrites) {
const headers = overwrites.headers.reduce((headers, [header, value]) => {
headers[header] = value;
return headers;
}, {});
response.writeHead(response.statusCode, headers);
}
const koaReply = (response, body, statusCode) => {
const overwrites = getOverwrites(response, statusCode);
response.ctx.respond = false;
response.status = statusCode || overwrites.status;
const { writable, status, ctx, res: rawResponse } = response;
const { headersSent } = rawResponse;
if (!writable) {
return;
}
// Empty response
if ([null, undefined].includes(body)) {
applyOverwrites(rawResponse, overwrites);
body =
ctx.req.httpVersionMajor >= 2
? String(status)
: ctx.message || String(status);
if (!headersSent) {
ctx.type = 'text';
ctx.length = Buffer.byteLength(body);
}
rawResponse.end(body);
return;
}
response.body = body;
applyOverwrites(rawResponse, overwrites);
// Other responses
switch (true) {
case Buffer.isBuffer(body):
case typeof body === 'string':
rawResponse.end(body);
return;
case body instanceof stream_1.Stream:
body.pipe(rawResponse);
return;
default:
const stringifiedBody = JSON.stringify(body);
if (!headersSent) {
ctx.length = Buffer.byteLength(stringifiedBody);
}
rawResponse.end(stringifiedBody);
return;
}
};
exports.koaReply = koaReply;
//# sourceMappingURL=KoaReply.js.map