32 lines
940 B
TypeScript
Raw Normal View History

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";
2024-11-06 14:53:07 +07:00
export const BASE_API_URL = process.env.EXPO_PUBLIC_API_URL || ""; //"http://10.0.0.100:3000";
export const BASE_WS_URL = BASE_API_URL.replace("http", "ws");
2024-11-08 18:24:08 +07:00
const api = ofetch.create({
baseURL: BASE_API_URL,
onRequest: (config) => {
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;