From 8f44593d55c82197854d9e29174fe66c4e50ebde Mon Sep 17 00:00:00 2001 From: Alexis Hovorka Date: Sat, 17 Feb 2024 00:42:20 -0700 Subject: [refactor] Switch to ES Modules --- app/utils.js | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) (limited to 'app/utils.js') diff --git a/app/utils.js b/app/utils.js index 2ff2b9c..03e2233 100644 --- a/app/utils.js +++ b/app/utils.js @@ -1,23 +1,31 @@ -"use strict"; - -const ct = module.exports.ct = (res, mime, code, head) => +export const 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)); } +export const 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")); +export const res204 = (res) => { res.statusCode = 204; res.end(); } +export const err400 = (res, msg) => { ct(res, "text/plain", 400); res.end(""+(msg||"400 Bad Request")); } +export const err401 = (res, msg) => { ct(res, "text/plain", 401); res.end(""+(msg||"401 Unauthorized")); } +export const err403 = (res, msg) => { ct(res, "text/plain", 403); res.end(""+(msg||"403 Forbidden")); } +export const err404 = (res, msg) => { ct(res, "text/plain", 404); res.end(""+(msg||"404 Not Found")); } +export const 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) => { +export const 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 => +export const parseCookies = req => req.headers.cookie?.split(";") .map(c => c.split("=").map(s => decodeURIComponent(s.trim()))) .reduce((a,c) => (a[c[0]]=c[1],a), {}); + +export const clamp = (x,l,h) => Math.max(l,Math.min(x,h)); + +export function deepFreeze(obj) { + for (const name of Reflect.ownKeys(obj)) { + const value = obj[name]; + if ((value && typeof value === "object") || + typeof value === "function") deepFreeze(value); + } return Object.freeze(obj); +} -- cgit v1.2.3-70-g09d2