summaryrefslogtreecommitdiff
path: root/app/utils.js
blob: 03e22336a120843697e4d94965265990306637bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
export const ct = (res, mime, code, head) =>
  res.writeHead(code||200, Object.apply({"Content-Type": mime||"application/json"}, head));
export const sj = (res, data, {code, head}={}) => { ct(res, null, code, head); res.end(JSON.stringify(data)); }

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

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

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