diff options
author | Alexis Hovorka <[email protected]> | 2024-02-13 23:10:49 -0700 |
---|---|---|
committer | Alexis Hovorka <[email protected]> | 2024-02-13 23:10:49 -0700 |
commit | af96e03db9eab2a468561d1d82a32e8a7b01da90 (patch) | |
tree | 19d4d19be1a7c6deaf679cdd3727ef7b64e8cebd | |
parent | c698ccab0cffe7212ef86da88a5f1da4ee81f5c8 (diff) |
[feat] Centralize basic utility functions
-rw-r--r-- | app/utils.js | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/app/utils.js b/app/utils.js new file mode 100644 index 0000000..2ff2b9c --- /dev/null +++ b/app/utils.js @@ -0,0 +1,23 @@ +"use strict"; + +const ct = module.exports.ct = (res, mime, code, head) => + res.writeHead(code||200, Object.apply({"Content-Type": mime||"application/json"}, head)); +module.exports.sj = (res, data, {code, head}={}) => { ct(res, null, code, head); res.end(JSON.stringify(data)); } + +module.exports.res204 = (res) => { res.statusCode = 204; res.end(); } +module.exports.err400 = (res, msg) => { ct(res, "text/plain", 400); res.end(""+(msg||"400 Bad Request")); } +module.exports.err401 = (res, msg) => { ct(res, "text/plain", 401); res.end(""+(msg||"401 Unauthorized")); } +module.exports.err403 = (res, msg) => { ct(res, "text/plain", 403); res.end(""+(msg||"403 Forbidden")); } +module.exports.err404 = (res, msg) => { ct(res, "text/plain", 404); res.end(""+(msg||"404 Not Found")); } +module.exports.err500 = (res, msg) => { ct(res, "text/plain", 500); res.end(""+(msg||"500 Internal Server Error")); + console.log(Date.now+" [ERROR] 500"); } + +module.exports.cors = fn => (req, res, ...rest) => { + res.setHeader("Access-Control-Allow-Origin", "*"); + res.setHeader("Access-Control-Allow-Methods", "GET, POST"); + fn(req, res, ...rest); }; + +module.exports.parseCookies = req => + req.headers.cookie?.split(";") + .map(c => c.split("=").map(s => decodeURIComponent(s.trim()))) + .reduce((a,c) => (a[c[0]]=c[1],a), {}); |