OpenAuth_views/src/request.ts

44 lines
1.3 KiB
TypeScript

import { getCookie } from "./cookie";
// const baseURL = "https://auth.stamm.me";
// const baseURL = "http://localhost:3000";
const baseURL = "";
export default async function request(endpoint: string, parameters: { [key: string]: string } = {}, method: "GET" | "POST" | "DELETE" | "PUT" = "GET", body?: any, authInParam = 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 (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 Error(data.error))
}
return data;
})
}