File size: 2,309 Bytes
eb4179c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import axios from 'axios';

const api = axios.create({
    baseURL: (window.location.hostname === '127.0.0.1' || window.location.port === '5173')
        ? 'http://localhost:3000/api'
        : '/api',
    headers: {
        'Content-Type': 'application/json'
    }
});

// Intercept requests and attach the JWT token if available
api.interceptors.request.use((config) => {
    const token = localStorage.getItem('admin_token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
});

// Intercept responses for auth errors globally
api.interceptors.response.use(
    response => response,
    error => {
        if (error.response && error.response.status === 401) {
            localStorage.removeItem('admin_token');
            if (window.location.pathname !== '/login') {
                window.location.href = '/login';
            }
        }
        return Promise.reject(error);
    }
);

export const authAPI = {
    login: async (password) => {
        const { data } = await api.post('/settings/admin-login', { password });
        return data;
    }
};

export const ordersAPI = {
    getAll: async () => {
        const { data } = await api.get('/orders');
        return data;
    },
    updateStatus: async (orderId, status) => {
        const { data } = await api.put(`/orders/${orderId}/status`, { status });
        return data;
    }
};

export const productsAPI = {
    getAll: async () => {
        const { data } = await api.get('/products');
        return data;
    },
    create: async (productData) => {
        const { data } = await api.post('/products', productData);
        return data;
    },
    update: async (id, productData) => {
        const { data } = await api.put(`/products/${id}`, productData);
        return data;
    },
    delete: async (id) => {
        const { data } = await api.delete(`/products/${id}`);
        return data;
    }
};

export const settingsAPI = {
    get: async () => {
        const { data } = await api.get('/settings');
        return data;
    },
    update: async (settingsData) => {
        const { data } = await api.put('/settings', settingsData);
        return data;
    }
};

export default api;