aboutsummaryrefslogtreecommitdiff
path: root/web/pw-server/src/lib/utils.ts
blob: 155d9525b178ea5f2ba7544e3a637c0bae40f4a5 (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
import { get_session_token } from "./auth";

export function debounce(func: Function, timeout: number = 300) {
  let timer: ReturnType<typeof setTimeout>;
  return (...args: any[]) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}

export async function get(url: string, fetch_fn: Function = fetch) {
  const headers = { "Content-Type": "application/json" };

  const token = get_session_token();
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const response = await fetch_fn(url, {
    method: "GET",
    headers,
  });

  return JSON.parse(response);
}

export async function post(url: string, data: any, fetch_fn: Function = fetch) {
  const headers = { "Content-Type": "application/json" };

  const token = get_session_token();
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const response = await fetch_fn(url, {
    method: "POST",
    headers,
    body: JSON.stringify(data),
  });

  return JSON.parse(response);
}