88 lines
2.2 KiB
JavaScript
88 lines
2.2 KiB
JavaScript
|
|
import axios from 'axios'
|
||
|
|
|
||
|
|
const api = axios.create({
|
||
|
|
baseURL: '/api',
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
},
|
||
|
|
})
|
||
|
|
|
||
|
|
// Add token to requests if available
|
||
|
|
api.interceptors.request.use(
|
||
|
|
(config) => {
|
||
|
|
const token = localStorage.getItem('token')
|
||
|
|
if (token) {
|
||
|
|
config.headers.Authorization = `Bearer ${token}`
|
||
|
|
}
|
||
|
|
return config
|
||
|
|
},
|
||
|
|
(error) => Promise.reject(error)
|
||
|
|
)
|
||
|
|
|
||
|
|
// Handle response errors
|
||
|
|
api.interceptors.response.use(
|
||
|
|
(response) => response,
|
||
|
|
(error) => {
|
||
|
|
if (error.response?.status === 401) {
|
||
|
|
// Token expired or invalid
|
||
|
|
localStorage.removeItem('token')
|
||
|
|
localStorage.removeItem('user')
|
||
|
|
window.location.href = '/login'
|
||
|
|
}
|
||
|
|
return Promise.reject(error)
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
export function useApi() {
|
||
|
|
return {
|
||
|
|
// Auth
|
||
|
|
login: async (email, password) => {
|
||
|
|
const response = await api.post('/auth/login', { email, password })
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
register: async (userData) => {
|
||
|
|
const response = await api.post('/auth/register', userData)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
getCurrentUser: async () => {
|
||
|
|
const response = await api.get('/users/me')
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
|
||
|
|
// Products
|
||
|
|
getProducts: async () => {
|
||
|
|
const response = await api.get('/products')
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
getProduct: async (id) => {
|
||
|
|
const response = await api.get(`/products/${id}`)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
createProduct: async (productData) => {
|
||
|
|
const response = await api.post('/products', productData)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
updateProduct: async (id, productData) => {
|
||
|
|
const response = await api.put(`/products/${id}`, productData)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
deleteProduct: async (id) => {
|
||
|
|
const response = await api.delete(`/products/${id}`)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
|
||
|
|
// Orders
|
||
|
|
getOrders: async () => {
|
||
|
|
const response = await api.get('/orders')
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
getOrder: async (id) => {
|
||
|
|
const response = await api.get(`/orders/${id}`)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
createOrder: async (orderData) => {
|
||
|
|
const response = await api.post('/orders', orderData)
|
||
|
|
return response.data
|
||
|
|
},
|
||
|
|
}
|
||
|
|
}
|