File size: 1,521 Bytes
9bf5b63
e22a97b
 
 
7e23b23
e22a97b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// <reference types="vite/client" />
import axios from "axios"

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:7860"
console.log("Using API Base URL:", API_BASE_URL);

const apiClient = axios.create({
    baseURL: API_BASE_URL,
    headers: {
        "Content-Type": "application/json",
    },
})

// Add a request interceptor to include tenant_id and auth token
apiClient.interceptors.request.use((config) => {
    const tenant_id = localStorage.getItem("tenant_id")
    const access_token = localStorage.getItem("access_token")

    if (tenant_id) {
        config.headers["X-Tenant-ID"] = tenant_id
    }

    if (access_token) {
        config.headers.Authorization = `Bearer ${access_token}`
    }

    return config
})

// Add a response interceptor for error handling
apiClient.interceptors.response.use(
    (response) => response,
    (error) => {
        // Handle transient errors or backend cold starts
        if (error.code === 'ECONNABORTED' || error.message.includes('Network Error')) {
            console.error("Backend might be cold-starting or unreachable.")
        }

        // Redirect to login on 401 Unauthorized (except for login/register endpoints)
        if (error.response?.status === 401 && !error.config.url?.includes('/auth/')) {
            localStorage.removeItem("access_token")
            window.location.href = "/login"
        }

        return Promise.reject(error)
    }
)

export default apiClient