OpenAuth_server/Frontend/src/helper/request.ts

63 lines
1.5 KiB
TypeScript

import { getCookie } from "./cookie";
const baseURL = "";
export class RequestError extends Error {
response: any;
constructor(message: string, response: any) {
super(message);
this.name = "RequestError";
this.response = response;
}
}
export default async function request(
endpoint: string,
parameters: { [key: string]: string } = {},
method: "GET" | "POST" | "DELETE" | "PUT" = "GET",
body?: any,
authInParam = false,
redirect = false
) {
let pairs = [];
if (authInParam) {
parameters.login = getCookie("login");
parameters.special = getCookie("special");
}
for (let key in parameters) {
pairs.push(key + "=" + parameters[key]);
}
let url = endpoint;
if (pairs.length > 0) {
url += "?" + pairs.join("&");
}
return fetch(baseURL + url, {
method,
body: JSON.stringify(body),
credentials: "same-origin",
headers: {
"content-type": "application/json",
},
})
.then((e) => {
if (e.status !== 200) throw new Error(e.statusText);
return e.json();
})
.then((data) => {
if (data.error) {
if (redirect && data.additional && data.additional.auth) {
let state = btoa(
window.location.pathname + window.location.hash
);
window.location.href = `/login?state=${state}&base64=true`;
}
return Promise.reject(new RequestError(data.error, data));
}
return data;
});
}