37 lines
979 B
TypeScript
Raw Normal View History

2024-11-12 04:43:59 +07:00
import { getCurrentServer } from "@/stores/app";
import authStore from "@/stores/auth";
2024-11-09 10:33:07 +00:00
import { QueryClient } from "@tanstack/react-query";
2024-11-08 18:24:08 +07:00
import { ofetch } from "ofetch";
const api = ofetch.create({
onRequest: (config) => {
2024-11-12 04:43:59 +07:00
const server = getCurrentServer();
if (!server) {
throw new Error("No server selected");
}
// set server url
config.options.baseURL = server.url;
const authToken = authStore.getState().token;
if (authToken) {
config.options.headers.set("Authorization", `Bearer ${authToken}`);
}
},
2024-11-09 14:37:09 +00:00
onResponseError: (error) => {
if (error.response.status === 401 && !!authStore.getState().token) {
authStore.setState({ token: null });
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
});
2024-11-09 10:33:07 +00:00
export const queryClient = new QueryClient();
2024-11-08 18:24:08 +07:00
export default api;