2022-02-01 15:24:45 -05:00
|
|
|
import axios from 'axios';
|
2022-04-07 07:26:52 -04:00
|
|
|
import * as Sentry from '@sentry/browser';
|
2022-02-01 15:24:45 -05:00
|
|
|
|
2022-04-07 09:21:57 -04:00
|
|
|
const baseUrl = () => window.location.origin.includes("localhost") ? "http://localhost:5000" : localStorage.isBeta ? "https://api.beta.pluralkit.me" : "https://api.pluralkit.me";
|
2022-02-01 15:24:45 -05:00
|
|
|
|
|
|
|
|
const methods = ['get', 'post', 'delete', 'patch', 'put'];
|
|
|
|
|
const noop = () => {};
|
|
|
|
|
|
2022-04-07 06:30:51 -04:00
|
|
|
const scheduled = [];
|
|
|
|
|
const runAPI = () => {
|
|
|
|
|
if (scheduled.length == 0) return;
|
|
|
|
|
const {axiosData, res, rej} = scheduled.shift();
|
2022-04-07 07:26:52 -04:00
|
|
|
axios(axiosData)
|
|
|
|
|
.then((resp) => res(parseData(resp.status, resp.data)))
|
|
|
|
|
.catch((err) => {
|
|
|
|
|
Sentry.captureException("Fetch error", err);
|
|
|
|
|
rej(err);
|
|
|
|
|
});
|
2022-04-07 06:30:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setInterval(runAPI, 500);
|
|
|
|
|
|
2022-02-01 15:24:45 -05:00
|
|
|
export default function() {
|
|
|
|
|
const route = [];
|
|
|
|
|
const handler = {
|
|
|
|
|
get(_, name) {
|
|
|
|
|
if (route.length == 0 && name != "private")
|
|
|
|
|
route.push("v2");
|
|
|
|
|
if (methods.includes(name)) {
|
2022-04-07 06:30:51 -04:00
|
|
|
return ({ data = undefined, auth = true, token = null, query = null } = {}) => new Promise((res, rej) => scheduled.push({ res, rej, axiosData: {
|
2022-02-01 15:24:45 -05:00
|
|
|
url: baseUrl() + "/" + route.join("/") + (query ? `?${Object.keys(query).map(x => `${x}=${query[x]}`).join("&")}` : ""),
|
|
|
|
|
method: name,
|
|
|
|
|
headers: {
|
|
|
|
|
authorization: token ?? (auth ? localStorage.getItem("pk-token") : undefined),
|
|
|
|
|
"content-type": name == "get" ? undefined : "application/json"
|
|
|
|
|
},
|
|
|
|
|
data: !!data ? JSON.stringify(data) : undefined,
|
|
|
|
|
validateStatus: () => true,
|
2022-04-07 06:30:51 -04:00
|
|
|
}}));
|
2021-12-09 12:53:54 +01:00
|
|
|
}
|
2022-02-01 15:24:45 -05:00
|
|
|
route.push(name);
|
|
|
|
|
return new Proxy(noop, handler);
|
|
|
|
|
},
|
|
|
|
|
apply(target, _, args) {
|
|
|
|
|
route.push(...args.filter(x => x != null));
|
|
|
|
|
return new Proxy(noop, handler);
|
2021-12-09 12:53:54 +01:00
|
|
|
}
|
|
|
|
|
}
|
2022-02-01 15:24:45 -05:00
|
|
|
return new Proxy(noop, handler);
|
|
|
|
|
}
|
2021-12-09 12:53:54 +01:00
|
|
|
|
2022-02-01 15:24:45 -05:00
|
|
|
import * as errors from './errors';
|
2021-12-09 12:53:54 +01:00
|
|
|
|
2022-02-01 15:24:45 -05:00
|
|
|
function parseData(code: number, data: any) {
|
|
|
|
|
if (code == 200) return data;
|
|
|
|
|
if (code == 204) return;
|
|
|
|
|
throw errors.parse(code, data);
|
2021-12-09 12:53:54 +01:00
|
|
|
}
|