File size: 2,223 Bytes
9e497a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b6531
 
 
d20d896
09b6531
 
9e497a6
09b6531
9e497a6
5e005fe
 
9e497a6
 
 
 
 
 
5bef62b
 
 
9e497a6
 
 
 
 
 
18f750b
 
3ab7243
 
 
 
 
 
18f750b
9e497a6
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
export const setToken = (token: string) => {
    if (typeof window !== 'undefined') {
        localStorage.setItem('tg_auth_token', token);
    }
};

export const getToken = () => {
    if (typeof window !== 'undefined') {
        return localStorage.getItem('tg_auth_token');
    }
    return null;
};

export const removeToken = () => {
    if (typeof window !== 'undefined') {
        localStorage.removeItem('tg_auth_token');
    }
};

export const getAuthHeaders = (): Record<string, string> => {
    const token = getToken();
    return token ? { Authorization: `Bearer ${token}` } : {};
};

export const getApiBase = (): string => {
    const envBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/$/, '');
    if (envBase) return envBase;
    return 'https://arkitel.onrender.com';
};

export const apiFetch = async (endpoint: string, options: any = {}) => {
    const apiBase = getApiBase();
    const isAbsolute = /^https?:\/\//i.test(endpoint);
    // On production/when apiBase is set, we want ALL /api calls to go to the backend
    const url = isAbsolute ? endpoint : (apiBase ? `${apiBase}${endpoint}` : endpoint);

    const method = (options.method || 'GET').toUpperCase();
    const defaultHeaders: Record<string, string> = {
        ...getAuthHeaders(),
    };
    if (method !== 'GET' && options.body && !('Content-Type' in (options.headers || {}))) {
        if (typeof FormData === 'undefined' || !(options.body instanceof FormData)) {
            defaultHeaders['Content-Type'] = 'application/json';
        }
    }
    const headers = { ...defaultHeaders, ...(options.headers || {}) };

    const response = await fetch(url, { ...options, method, headers });

    if (response.status === 401) {
        removeToken();
        if (typeof window !== 'undefined') {
            const path = window.location.pathname;
            const isPublicRoute = path === '/' || path === '/get-started' || path === '/login' || path === '/register' || path === '/admin/login';
            if (!isPublicRoute) {
                const isAdminPath = path.startsWith('/admin');
                window.location.href = isAdminPath ? '/admin/login' : '/login';
            }
        }
    }

    return response;
};