File size: 2,387 Bytes
2dddd1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)
};