filebrowser/frontend/src/api/utils.js

81 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-03-21 11:51:58 +00:00
import store from "@/store";
2022-05-04 12:58:19 +00:00
import { renew, logout } from "@/utils/auth";
2021-03-21 11:51:58 +00:00
import { baseURL } from "@/utils/constants";
2022-05-02 13:47:22 +00:00
import { encodePath } from "@/utils/url";
2022-05-04 12:58:19 +00:00
export async function fetchURL(url, opts, auth = true) {
2021-03-21 11:51:58 +00:00
opts = opts || {};
opts.headers = opts.headers || {};
2021-03-21 11:51:58 +00:00
let { headers, ...rest } = opts;
2021-04-16 14:01:10 +00:00
let res;
try {
res = await fetch(`${baseURL}${url}`, {
headers: {
"X-Auth": store.state.jwt,
...headers,
},
...rest,
});
2022-05-04 12:36:13 +00:00
} catch {
const error = new Error("000 No connection");
error.status = 0;
throw error;
2021-04-16 14:01:10 +00:00
}
2022-05-04 12:58:19 +00:00
if (auth && res.headers.get("X-Renew-Token") === "true") {
2021-03-21 11:51:58 +00:00
await renew(store.state.jwt);
}
if (res.status < 200 || res.status > 299) {
const error = new Error(await res.text());
error.status = res.status;
2022-05-04 12:58:19 +00:00
if (auth && res.status == 401) {
logout();
}
throw error;
}
2021-03-21 11:51:58 +00:00
return res;
}
2021-03-21 11:51:58 +00:00
export async function fetchJSON(url, opts) {
const res = await fetchURL(url, opts);
if (res.status === 200) {
2021-03-21 11:51:58 +00:00
return res.json();
} else {
2021-03-21 11:51:58 +00:00
throw new Error(res.status);
}
}
2021-03-21 11:51:58 +00:00
export function removePrefix(url) {
url = url.split("/").splice(2).join("/");
2021-03-21 11:51:58 +00:00
if (url === "") url = "/";
if (url[0] !== "/") url = "/" + url;
return url;
}
2022-05-02 13:47:22 +00:00
export function createURL(endpoint, params = {}, auth = true) {
let prefix = baseURL;
2022-06-10 10:05:05 +00:00
if (!prefix.endsWith("/")) {
prefix = prefix + "/";
}
const url = new URL(prefix + encodePath(endpoint), origin);
2022-05-02 13:47:22 +00:00
const searchParams = {
...(auth && { auth: store.state.jwt }),
...params,
};
for (const key in searchParams) {
url.searchParams.set(key, searchParams[key]);
}
return url.toString();
}