summaryrefslogtreecommitdiff
path: root/src/lib/server/cookiebridge.ts
blob: 778fc2cc9fc0eb6b0a9ab9950292beca0ccac0ad (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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { getContext, getContextData } from "waku/middleware/context";

const useCookies = () => {
  const ctx = getContext();
  const headers = ctx.req.headers;
  console.log(headers.cookie);

  const getCookie = (s: string) => {
    const coki = headers.cookie;
    if (!coki) return {};
    const cokiMap = parseCoki(coki);
    return cokiMap;
  };
  const setCookie = (s: string) => {
    const ctxdata = getContextData();
    // (ctxdata.cokimap as Record<string, string>).sorlang = s;
    // ctxdata.cookie = `sorlang=${s}; Secure`
    ctxdata.cookie = `sorlang=${s};`;
  };
  const delCookie = (s: string) => {
    const ctxdata = getContextData();
    delete (ctxdata.cokimap as Record<string, string>).sorlang;
  };
  return { getCookie, setCookie, delCookie };
};

export { useCookies };

function parseCoki(s: string) {
  return s
    .split(";")
    .map((v) => v.split("="))
    .reduce((acc: Record<string, string>, v: any) => {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
      return acc;
    }, {});
}
function parseSetCoki(s: string) {
  return s
    .split(";")
    .map((v) => v.split("="))
    .reduce((acc: Record<string, string>, v: any) => {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
      return acc;
    }, {});
}
function cokiToString(m: Record<string, string>): string {
  return Object.entries(m).reduce((acc: string, item: [string, string]) => {
    const [key, val] = item;
    return `${acc} ${key}=${val};`;
  }, "");
}