From 2c77caf4f55d278a2c4a0c73c5ef228e5f5a1706 Mon Sep 17 00:00:00 2001 From: Flummi Date: Sat, 26 Mar 2022 20:10:47 +0100 Subject: [PATCH] json reply: auto stringify and proper codes --- package.json | 2 +- src/index.mjs | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 4edad19..2690538 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "flummpress", - "version": "2.0.2", + "version": "2.0.3", "description": "Express für arme", "main": "src/index.mjs", "repository": { diff --git a/src/index.mjs b/src/index.mjs index b3bfda7..37dd5b8 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -108,8 +108,12 @@ export default class flummpress { type = "text/html", body }) => res.writeHead(code, { "Content-Type": `${type}; charset=utf-8` }).end(body); - res.json = msg => res.reply({ type: "application/json", body: msg }); - res.html = msg => res.reply({ type: "text/html", body: msg }); + res.json = (body, code = 200) => { + if(typeof body === 'object') + body = JSON.stringify(body); + return res.reply({ code, body, type: "application/json" }); + }; + res.html = (body, code = 200) => res.reply({ code, body, type: "text/html" }); res.redirect = (target, code = 307) => res.writeHead(code, { "Cache-Control": "no-cache, public", "Location": target @@ -122,5 +126,4 @@ export default class flummpress { return new Promise(resolve => resolve(true)); return new Promise(resolve => middleware(req, res, () => resolve(true))); }; - };