2024-11-12 04:43:59 +07:00
|
|
|
import { getCurrentServer } from "@/stores/app";
|
2024-11-14 17:58:19 +07:00
|
|
|
import authStore, { logout } from "@/stores/auth";
|
2024-11-08 18:24:08 +07:00
|
|
|
import { ofetch } from "ofetch";
|
|
|
|
|
|
|
|
const api = ofetch.create({
|
2024-11-10 18:49:18 +07:00
|
|
|
onRequest: (config) => {
|
2024-11-12 04:43:59 +07:00
|
|
|
const server = getCurrentServer();
|
|
|
|
if (!server) {
|
|
|
|
throw new Error("No server selected");
|
|
|
|
}
|
|
|
|
|
|
|
|
// set server url
|
2024-11-16 02:34:07 +07:00
|
|
|
config.options.baseURL = server;
|
2024-11-12 04:43:59 +07:00
|
|
|
|
2024-11-12 17:17:10 +00:00
|
|
|
const { token, teamId } = authStore.getState();
|
|
|
|
|
|
|
|
if (token) {
|
|
|
|
config.options.headers.set("Authorization", `Bearer ${token}`);
|
|
|
|
}
|
|
|
|
if (teamId) {
|
|
|
|
config.options.headers.set("X-Team-Id", teamId);
|
2024-11-10 18:49:18 +07:00
|
|
|
}
|
|
|
|
},
|
2024-11-09 14:37:09 +00:00
|
|
|
onResponseError: (error) => {
|
2024-11-10 18:49:18 +07:00
|
|
|
if (error.response.status === 401 && !!authStore.getState().token) {
|
2024-11-14 17:58:19 +07:00
|
|
|
logout();
|
2024-11-10 18:49:18 +07:00
|
|
|
throw new Error("Unauthorized");
|
|
|
|
}
|
|
|
|
|
2024-11-09 14:37:09 +00:00
|
|
|
if (error.response._data) {
|
|
|
|
const message = error.response._data.message;
|
|
|
|
throw new Error(message || "Something went wrong");
|
|
|
|
}
|
|
|
|
},
|
2024-11-08 18:24:08 +07:00
|
|
|
});
|
|
|
|
|
|
|
|
export default api;
|