client.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import axios from "axios";
  2. import { useAuthStore } from "@/stores/auth";
  3. import { mockAxiosResponse, mockMode } from "./mock";
  4. export const apiClient = axios.create({
  5. baseURL: "/gateway",
  6. timeout: 20000,
  7. });
  8. apiClient.interceptors.request.use((config) => {
  9. if (mockMode) {
  10. config.adapter = async (adapterConfig) => mockAxiosResponse(adapterConfig);
  11. }
  12. const { apiKey, userId } = useAuthStore.getState();
  13. if (apiKey) config.headers.set("x-api-key", apiKey);
  14. if (userId) config.headers.set("x-user-id", userId);
  15. return config;
  16. });
  17. apiClient.interceptors.response.use(
  18. (response) => response,
  19. (error) => {
  20. if (error.config && (error.response?.status === 404 || !error.response)) {
  21. return Promise.resolve(mockAxiosResponse(error.config));
  22. }
  23. if (error.response?.status === 401) {
  24. useAuthStore.getState().logout();
  25. if (window.location.pathname !== "/login") {
  26. window.location.assign("/login");
  27. }
  28. }
  29. return Promise.reject(error);
  30. },
  31. );
  32. export function tenantParams(extra?: Record<string, string | number | boolean | undefined | null>) {
  33. return { ...extra };
  34. }