1const getApiRoot = () => {
2 if (localStorage.getItem("currentNode") !== null && localStorage.getItem("currentNode") !== "0") {
3 return "/api/nodes/" + localStorage.getItem("currentNode");
4 } else return "/api";
5}
6
7// Get the default headers of the request
8const getHeaders = () => {
9 const password = localStorage.getItem("password");
10 let headers = password ? {"x-password": encodeURIComponent(password)} : {};
11 headers['content-type'] = 'application/json';
12
13 return headers;
14}
15
16// Run a plain request with all default values using the base path
17export const baseRequest = async (path, method = "GET", body = {}, headers = {}) => {
18 const controller = new AbortController();
19 setTimeout(() => controller.abort(), 10000);
20 return await fetch("/api" + path, {
21 headers: {...getHeaders(), ...headers}, method,
22 body: method !== "GET" ? JSON.stringify(body) : undefined,
23 signal: controller.signal
24 });
25}
26
27// Run a plain request with all default values
28export const request = async (path, method = "GET", body = {}, headers = {}) => {
29 return await fetch(getApiRoot() + path, {
30 headers: {...getHeaders(), ...headers}, method,
31 body: method !== "GET" ? JSON.stringify(body) : undefined
32 });
33}
34
35// Run a GET request and get the json of the response
36export const jsonRequest = async (path, headers = {}) => {
37 return (await request(path, "GET", null, headers)).json();
38}
39
40// Run a POST request and post some values
41export const postRequest = async (path, body = {}, headers = {}) => {
42 return await request(path, "POST", body, headers);
43}
44
45// Run a PUT request update a resource
46export const putRequest = async (path, body = {}, headers = {}) => {
47 return await request(path, "PUT", body, headers);
48}
49
50// Run a PATCH request update a resource
51export const patchRequest = async (path, body = {}, headers = {}) => {
52 return await request(path, "PATCH", body, headers);
53}
54
55// Run a DELETE request and delete a resource
56export const deleteRequest = async (path, body = {}, headers = {}) => {
57 return await request(path, "DELETE", body, headers);
58}
59
60// Download a specific file from the response output
61export const downloadRequest = async (path, body = {}, headers = {}) => {
62 const file = await request(path, "GET", body, headers);
63 let element = document.createElement('a');
64 let url = file.headers.get('Content-Disposition').split('filename=')[1];
65 element.setAttribute("download", url.replaceAll("\"", ""));
66
67 const blob = await file.blob();
68 element.href = window.URL.createObjectURL(blob);
69 document.body.appendChild(element);
70 element.click();
71 element.remove();
72}