File size: 5,596 Bytes
452f691
 
 
 
dd7ffbd
 
452f691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68aff21
 
452f691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
 
 
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
dd7ffbd
452f691
 
 
 
dd7ffbd
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
const DEFAULT_TTL = 60 * 1000; // 1 minute cache

class ApiClient {
    constructor() {
        const origin = window?.location?.origin ?? '';
        this.baseURL = origin.replace(/\/$/, '');
        this.cache = new Map();
        this.requestLogs = [];
        this.errorLogs = [];
        this.logSubscribers = new Set();
        this.errorSubscribers = new Set();
    }

    buildUrl(endpoint) {
        if (!endpoint.startsWith('/')) {
            return `${this.baseURL}/${endpoint}`;
        }
        return `${this.baseURL}${endpoint}`;
    }

    notifyLog(entry) {
        this.requestLogs.push(entry);
        this.requestLogs = this.requestLogs.slice(-100);
        this.logSubscribers.forEach((cb) => cb(entry));
    }

    notifyError(entry) {
        this.errorLogs.push(entry);
        this.errorLogs = this.errorLogs.slice(-100);
        this.errorSubscribers.forEach((cb) => cb(entry));
    }

    onLog(callback) {
        this.logSubscribers.add(callback);
        return () => this.logSubscribers.delete(callback);
    }

    onError(callback) {
        this.errorSubscribers.add(callback);
        return () => this.errorSubscribers.delete(callback);
    }

    getLogs() {
        return [...this.requestLogs];
    }

    getErrors() {
        return [...this.errorLogs];
    }

    async request(method, endpoint, { body, cache = true, ttl = DEFAULT_TTL } = {}) {
        const url = this.buildUrl(endpoint);
        const cacheKey = `${method}:${url}`;

        if (method === 'GET' && cache && this.cache.has(cacheKey)) {
            const cached = this.cache.get(cacheKey);
            if (Date.now() - cached.timestamp < ttl) {
                return { ok: true, data: cached.data, cached: true };
            }
        }

        const started = performance.now();
        const randomId = (window.crypto && window.crypto.randomUUID && window.crypto.randomUUID())
            || `${Date.now()}-${Math.random()}`;
        const entry = {
            id: randomId,
            method,
            endpoint,
            status: 'pending',
            duration: 0,
            time: new Date().toISOString(),
        };

        try {
            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: body ? JSON.stringify(body) : undefined,
            });

            const duration = performance.now() - started;
            entry.duration = Math.round(duration);
            entry.status = response.status;

            const contentType = response.headers.get('content-type') || '';
            let data = null;
            if (contentType.includes('application/json')) {
                data = await response.json();
            } else if (contentType.includes('text')) {
                data = await response.text();
            }

            if (!response.ok) {
                const error = new Error((data && data.message) || response.statusText || 'Unknown error');
                error.status = response.status;
                throw error;
            }

            if (method === 'GET' && cache) {
                this.cache.set(cacheKey, { timestamp: Date.now(), data });
            }

            this.notifyLog({ ...entry, success: true });
            return { ok: true, data };
        } catch (error) {
            const duration = performance.now() - started;
            entry.duration = Math.round(duration);
            entry.status = error.status || 'error';
            this.notifyLog({ ...entry, success: false, error: error.message });
            this.notifyError({
                message: error.message,
                endpoint,
                method,
                time: new Date().toISOString(),
            });
            return { ok: false, error: error.message };
        }
    }

    get(endpoint, options) {
        return this.request('GET', endpoint, options);
    }

    post(endpoint, body, options = {}) {
        return this.request('POST', endpoint, { ...options, body });
    }

    // ===== Specific API helpers =====
    getHealth() {
        return this.get('/api/health');
    }

    getTopCoins(limit = 10) {
        return this.get(`/api/coins/top?limit=${limit}`);
    }

    getCoinDetails(symbol) {
        return this.get(`/api/coins/${symbol}`);
    }

    getMarketStats() {
        return this.get('/api/market/stats');
    }

    getLatestNews(limit = 20) {
        return this.get(`/api/news/latest?limit=${limit}`);
    }

    getProviders() {
        return this.get('/api/providers');
    }

    getPriceChart(symbol, timeframe = '7d') {
        return this.get(`/api/charts/price/${symbol}?timeframe=${timeframe}`);
    }

    analyzeChart(symbol, timeframe = '7d', indicators = []) {
        return this.post('/api/charts/analyze', { symbol, timeframe, indicators });
    }

    runQuery(payload) {
        return this.post('/api/query', payload);
    }

    analyzeSentiment(payload) {
        return this.post('/api/sentiment/analyze', payload);
    }

    summarizeNews(item) {
        return this.post('/api/news/summarize', item);
    }

    getDatasetsList() {
        return this.get('/api/datasets/list');
    }

    getDatasetSample(name) {
        return this.get(`/api/datasets/sample?name=${encodeURIComponent(name)}`);
    }

    getModelsList() {
        return this.get('/api/models/list');
    }

    testModel(payload) {
        return this.post('/api/models/test', payload);
    }
}

const apiClient = new ApiClient();
export default apiClient;