From a03abe678afd45e9d139e13c9d17a569c2853547 Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Sat, 16 Mar 2024 05:38:17 -0300 Subject: src/hero.mjs: interceptors.contentType(): Generate body from status when missing --- src/hero.mjs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'src/hero.mjs') diff --git a/src/hero.mjs b/src/hero.mjs index 5169284..b378887 100644 --- a/src/hero.mjs +++ b/src/hero.mjs @@ -71,15 +71,23 @@ export const interceptorsFn = ({ }, contentType: async (req, next) => { const response = await next(req); - const [mimeType, body] = typeof response.body === "string" ? - ["text/html", response.body] : - ["application/json", JSON.stringify(response.body) || ""]; + const { status, body, headers } = response; + assert.equal(typeof status, "number"); + const mappings = { + string: () => [ "text/html", body ], + undefined: () => [ "text/plain", http.STATUS_CODES[status] + "\n" ], + FALLBACK: () => [ "application/json", JSON.stringify(body) ], + }; + const type = typeof body; + assert.notEqual(type, "FALLBACK"); + const [mimeType, renderedBody] = + (mappings[type] || mappings.FALLBACK)(); return { ...response, - body, + body: renderedBody, headers: { "Content-Type": mimeType, - "Content-Length": Buffer.byteLength(body), + "Content-Length": Buffer.byteLength(renderedBody), ...(response.headers || {}) }, }; -- cgit v1.2.3