wallets-api / client /src /api.ts
z1amez's picture
v.1
2dddd1f
import axios from 'axios';
import type { Transaction, Wallet, Exchange, Loan } from './types';
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';
const apiClient = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json'
}
});
// Add a request interceptor to add the auth token
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Add a response interceptor for generic error handling
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401 || error.response?.status === 403) {
// Token expired or unauthorized, logout
localStorage.removeItem('auth_token');
localStorage.removeItem('auth_username');
window.location.href = '/login';
}
console.error('API Error:', error.response?.data || error.message);
return Promise.reject(error);
}
);
export const api = {
getRates: () => apiClient.get<Record<string, number>>('/rates').then(res => res.data),
getWallets: () => apiClient.get<Wallet[]>('/wallets').then(res => res.data),
getTransactions: () => apiClient.get<Transaction[]>('/transactions').then(res => res.data),
createTransaction: (data: Omit<Transaction, 'id'>) => apiClient.post('/transactions', data).then(res => res.data),
getExchanges: () => apiClient.get<Exchange[]>('/exchanges').then(res => res.data),
createExchange: (data: Omit<Exchange, 'id'>) => apiClient.post('/exchanges', data).then(res => res.data),
getLoans: () => apiClient.get<Loan[]>('/loans').then(res => res.data),
createLoan: (data: Omit<Loan, 'id'>) => apiClient.post('/loans', data).then(res => res.data),
updateLoan: (id: number, data: Omit<Loan, 'id'>) => apiClient.put(`/loans/${id}`, data).then(res => res.data),
deleteLoan: (id: number) => apiClient.delete(`/loans/${id}`).then(res => res.data),
payLoan: (id: number, amount: number) => apiClient.post(`/loans/${id}/pay`, { amount }).then(res => res.data),
getDashboardAnalytics: () => apiClient.get<any>('/analytics/dashboard').then(res => res.data)
};