Created the RequestUtil.js
This commit is contained in:
parent
004ee73299
commit
23e657b564
47
src/common/util/RequestUtil.js
Normal file
47
src/common/util/RequestUtil.js
Normal file
@ -0,0 +1,47 @@
|
||||
// Get the default headers of the request
|
||||
const getHeaders = () => {
|
||||
return localStorage.getItem("token") === undefined ? {Authorization: "Basic " + localStorage.getItem("token")} : {};
|
||||
}
|
||||
|
||||
// Run a plain request with all default values
|
||||
export const request = async (path, method = "GET", body = {}, headers = {}, abort = true) => {
|
||||
const controller = new AbortController();
|
||||
if (abort) setTimeout(() => {controller.abort()}, 10000);
|
||||
|
||||
|
||||
return await fetch("/api" + path, {
|
||||
headers: {"Content-Type": "application/json", ...getHeaders(), ...headers}, method,
|
||||
body: method !== "GET" ? JSON.stringify(body) : null,
|
||||
signal: controller.signal
|
||||
});
|
||||
}
|
||||
|
||||
// Run a GET request and get the json of the response
|
||||
export const jsonRequest = async (path, headers = {}) => {
|
||||
return (await request(path, "GET", null, headers)).json();
|
||||
}
|
||||
|
||||
// Dispatches the provided command
|
||||
export const dispatchCommand = (command) => {
|
||||
return postRequest("console", {command});
|
||||
}
|
||||
|
||||
// Run a POST request and post some values
|
||||
export const postRequest = async (path, body = {}, headers = {}) => {
|
||||
return await request(path, "POST", body, headers);
|
||||
}
|
||||
|
||||
// Run a PUT request update a resource
|
||||
export const putRequest = async (path, body = {}, headers = {}) => {
|
||||
return await request(path, "PUT", body, headers);
|
||||
}
|
||||
|
||||
// Run a PATCH request update a resource
|
||||
export const patchRequest = async (path, body = {}, headers = {}) => {
|
||||
return await request(path, "PATCH", body, headers);
|
||||
}
|
||||
|
||||
// Run a DELETE request and delete a resource
|
||||
export const deleteRequest = async (path, body = {}, headers = {}) => {
|
||||
return await request(path, "DELETE", body, headers);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user