json reply: auto stringify and proper codes

This commit is contained in:
Flummi 2022-03-26 20:10:47 +01:00
parent c3e9a3ab00
commit 2c77caf4f5
2 changed files with 7 additions and 4 deletions

View File

@ -1,6 +1,6 @@
{
"name": "flummpress",
"version": "2.0.2",
"version": "2.0.3",
"description": "Express für arme",
"main": "src/index.mjs",
"repository": {

View File

@ -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)));
};
};