91 lines
2.8 KiB
TypeScript
91 lines
2.8 KiB
TypeScript
import axios from 'axios';
|
|
import { RegisterData, UserData, ProductData, OrderData, AuthResponse } from '../types';
|
|
|
|
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: string, password: string): Promise<AuthResponse> => {
|
|
const response = await api.post<AuthResponse>('/auth/login', {
|
|
email,
|
|
password,
|
|
});
|
|
return response.data;
|
|
},
|
|
register: async (userData: RegisterData): Promise<AuthResponse> => {
|
|
const response = await api.post<AuthResponse>('/auth/register', userData);
|
|
return response.data;
|
|
},
|
|
getCurrentUser: async (): Promise<UserData> => {
|
|
const response = await api.get<UserData>('/users/me');
|
|
return response.data;
|
|
},
|
|
|
|
// Products
|
|
getProducts: async (): Promise<ProductData[]> => {
|
|
const response = await api.get<ProductData[]>('/products');
|
|
return response.data;
|
|
},
|
|
getProduct: async (id: string): Promise<ProductData> => {
|
|
const response = await api.get<ProductData>(`/products/${id}`);
|
|
return response.data;
|
|
},
|
|
createProduct: async (productData: Omit<ProductData, 'id'>): Promise<ProductData> => {
|
|
const response = await api.post<ProductData>('/products', productData);
|
|
return response.data;
|
|
},
|
|
updateProduct: async (id: string, productData: Partial<ProductData>): Promise<ProductData> => {
|
|
const response = await api.put<ProductData>(`/products/${id}`, productData);
|
|
return response.data;
|
|
},
|
|
deleteProduct: async (id: string): Promise<void> => {
|
|
await api.delete(`/products/${id}`);
|
|
},
|
|
|
|
// Orders
|
|
getOrders: async (): Promise<OrderData[]> => {
|
|
const response = await api.get<OrderData[]>('/orders');
|
|
return response.data;
|
|
},
|
|
getOrder: async (id: string): Promise<OrderData> => {
|
|
const response = await api.get<OrderData>(`/orders/${id}`);
|
|
return response.data;
|
|
},
|
|
createOrder: async (orderData: Omit<OrderData, 'id'>): Promise<OrderData> => {
|
|
const response = await api.post<OrderData>('/orders', orderData);
|
|
return response.data;
|
|
},
|
|
};
|
|
}
|