Repository navigation
Expand file tree
/
Copy pathapi.ts
More file actions
240 lines (211 loc) · 7.48 KB
/
Copy pathapi.ts
File metadata and controls
240 lines (211 loc) · 7.48 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import type {
SignupResponse,
AuthResponse,
ChatResponse,
DashboardSummary,
DatasetRecord,
MlResponse,
ReportResponse,
User,
UploadResponse,
DatasetPreviewResponse,
DatasetChartsResponse,
} from './types';
const API_BASE = import.meta.env.VITE_API_URL ?? '/api';
function authHeaders(token: string | null) {
const headers = new Headers();
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return headers;
}
async function requestJson<T>(path: string, options: RequestInit = {}, token: string | null = null): Promise<T> {
const headers = new Headers(options.headers ?? {});
if (!headers.has('Content-Type') && options.body && !(options.body instanceof FormData)) {
headers.set('Content-Type', 'application/json');
}
const authorizationHeaders = authHeaders(token);
authorizationHeaders.forEach((value, key) => headers.set(key, value));
const response = await fetch(`${API_BASE}${path}`, {
...options,
headers,
});
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: 'Request failed' }));
const detail = error?.detail;
if (Array.isArray(detail)) {
const message = detail
.map((item: { loc?: Array<string | number>; msg?: string }) => {
const field = item.loc?.filter((part) => part !== 'body').join('.') ?? 'request';
return `${field}: ${item.msg ?? 'invalid value'}`;
})
.join('; ');
throw new Error(message || 'Request failed');
}
if (typeof detail === 'string') {
throw new Error(detail);
}
throw new Error('Request failed');
}
return response.json() as Promise<T>;
}
export async function signup(email: string, password: string): Promise<SignupResponse> {
return requestJson<SignupResponse>('/auth/signup', {
method: 'POST',
body: JSON.stringify({ email: email.trim(), password }),
});
}
export async function registerAccount(payload: {
name: string;
age: number;
gender: 'Male' | 'Female' | 'Other';
email: string;
location: string;
password: string;
}): Promise<SignupResponse> {
return requestJson<SignupResponse>('/auth/signup', {
method: 'POST',
body: JSON.stringify(payload),
});
}
export async function verifyOtp(email: string, otp: string): Promise<AuthResponse> {
return requestJson<AuthResponse>('/auth/verify-otp', {
method: 'POST',
body: JSON.stringify({ email: email.trim(), otp }),
});
}
export async function resendOtp(email: string, password: string): Promise<SignupResponse> {
return requestJson<SignupResponse>('/auth/resend-otp', {
method: 'POST',
body: JSON.stringify({ email: email.trim(), password }),
});
}
export async function login(email: string, password: string): Promise<AuthResponse> {
return requestJson<AuthResponse>('/auth/login', {
method: 'POST',
body: JSON.stringify({ email: email.trim(), password }),
});
}
export async function fetchMe(token: string): Promise<User> {
return requestJson('/auth/me', { method: 'GET' }, token);
}
export async function fetchDashboardSummary(token: string, datasetId?: number): Promise<DashboardSummary> {
const suffix = datasetId ? `?dataset_id=${datasetId}` : '';
return requestJson<DashboardSummary>(`/dashboard/summary${suffix}`, { method: 'GET' }, token);
}
export async function fetchDashboardDatasets(token: string): Promise<{ datasets: DatasetRecord[] }> {
return requestJson<{ datasets: DatasetRecord[] }>('/dashboard/datasets', { method: 'GET' }, token);
}
export async function fetchDatasetPreview(
token: string,
datasetId: number,
page: number = 1,
pageSize: number = 50
): Promise<DatasetPreviewResponse> {
return requestJson<DatasetPreviewResponse>(
`/dashboard/dataset/${datasetId}/preview?page=${page}&page_size=${pageSize}`,
{ method: 'GET' },
token
);
}
export async function fetchDatasetCharts(token: string, datasetId: number): Promise<DatasetChartsResponse> {
return requestJson<DatasetChartsResponse>(
`/dashboard/dataset/${datasetId}/charts`,
{ method: 'GET' },
token
);
}
export async function uploadDataset(token: string, file: File): Promise<UploadResponse> {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${API_BASE}/datasets/upload`, {
method: 'POST',
headers: authHeaders(token),
body: formData,
});
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: 'Upload failed' }));
const detail = error?.detail;
if (Array.isArray(detail)) {
const message = detail
.map((item: { loc?: Array<string | number>; msg?: string }) => {
const field = item.loc?.filter((part) => part !== 'body').join('.') ?? 'request';
return `${field}: ${item.msg ?? 'invalid value'}`;
})
.join('; ');
throw new Error(message || 'Upload failed');
}
if (typeof detail === 'string') {
throw new Error(detail);
}
throw new Error('Upload failed. Please check file format.');
}
return response.json() as Promise<UploadResponse>;
}
export async function trainModel(token: string, datasetId: number, targetColumn: string, task?: string): Promise<MlResponse> {
return requestJson<MlResponse>(
'/ml/train',
{
method: 'POST',
body: JSON.stringify({ dataset_id: datasetId, target_column: targetColumn || null, task: task || null }),
},
token,
);
}
export async function askDataset(token: string, datasetId: number, question: string): Promise<ChatResponse> {
return requestJson<ChatResponse>(
'/chat/ask',
{
method: 'POST',
body: JSON.stringify({ dataset_id: datasetId, question }),
},
token,
);
}
export async function askChat(token: string, question: string, datasetId?: number): Promise<ChatResponse> {
return requestJson<ChatResponse>(
'/chat/ask',
{
method: 'POST',
body: JSON.stringify({ dataset_id: datasetId || 1, question }),
},
token,
);
}
export async function generateReport(token: string, datasetId: number, format: 'csv' | 'excel' | 'pdf'): Promise<ReportResponse> {
return requestJson<ReportResponse>(
'/report/generate',
{
method: 'POST',
body: JSON.stringify({ dataset_id: datasetId, format }),
},
token,
);
}
export function downloadReportUrl(reportName: string): string {
return `${API_BASE}/report/download/${encodeURIComponent(reportName)}`;
}
export function downloadModelUrl(artifactId: string, token: string): string {
// We open this URL directly — the browser will trigger a file download.
// We append the token as a query param because FileResponse doesn't support
// Authorization headers from window.open().
return `${API_BASE}/ml/download/${encodeURIComponent(artifactId)}?token=${encodeURIComponent(token)}`;
}
export async function forgotPassword(email: string): Promise<{ message: string }> {
return requestJson<{ message: string }>('/auth/forgot-password', {
method: 'POST',
body: JSON.stringify({ email: email.trim() }),
});
}
export async function verifyResetOtp(email: string, otp: string): Promise<{ message: string }> {
return requestJson<{ message: string }>('/auth/verify-reset-otp', {
method: 'POST',
body: JSON.stringify({ email: email.trim(), otp }),
});
}
export async function resetPassword(email: string, otp: string, newPassword: string): Promise<{ message: string }> {
return requestJson<{ message: string }>('/auth/reset-password', {
method: 'POST',
body: JSON.stringify({ email: email.trim(), otp, new_password: newPassword }),
});
}