-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
357 lines (312 loc) · 11.4 KB
/
api.js
File metadata and controls
357 lines (312 loc) · 11.4 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
* BlueMindsAPI Service Provider
* Comprehensive handler for Authentication, Therapy Sessions, and Game Analytics.
* @author Neuro-BlueMinds Team
* @version 2.2.0
*/
const KOYEB_URL = 'https://crude-sailfish-blueminds-65b642e8.koyeb.app/api';
const LOCAL_URL = 'http://localhost:8000/api';
class BlueMindsAPI {
constructor() {
/** @type {string} Dynamic Base URL selection */
//this.baseURL = window.location.hostname.includes('github.io') ? KOYEB_URL : LOCAL_URL;
this.baseURL = KOYEB_URL ;
/** @type {Object|null} Session User Data */
this.currentUser = this._loadUser();
/** @type {string|null} JWT Security Token */
this.token = localStorage.getItem('blueminds_token');
}
/**
* Internal helper to generate authorized headers.
* @private
*/
_getHeaders() {
const headers = { 'Content-Type': 'application/json' };
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
return headers;
}
async saveGameResults(gameData) {
console.log("save game results of ", gameData);
const response = await fetch(`${this.baseURL}/games/save-results`, {
method: 'POST',
headers: this._getHeaders(), // Aquí ya incluyes el token automáticamente
body: JSON.stringify(gameData)
});
if (!response.ok) throw new Error('Error al guardar resultados del juego');
return await response.json();
}
async getBestScore(gameId) {
const response = await fetch(`${this.baseURL}/games/best-score/${gameId}`, {
headers: this._getHeaders()
});
if (!response.ok) return 0;
const data = await response.json();
return data.bestScore; // Suponiendo que creamos este endpoint
}
// ========================================================================
// AUTHENTICATION MODULE
// ========================================================================
async register(name, birth, email, country, password, confirmPassword) {
const response = await fetch(`${this.baseURL}/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, birth, email, country, password, confirmPassword })
});
return this._handleAuthResponse(response);
}
async login(email, password) {
const response = await fetch(`${this.baseURL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
return this._handleAuthResponse(response);
}
async getQuizProgress() {
const response = await fetch(`${this.baseURL}/quiz/progress`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Error al obtener progreso');
const data = await response.json();
return data.progress;
}
async saveQuizResponse(data) {
console.log("Token: ", this.token);
// Desestructuramos para asegurar que enviamos los nombres que el backend espera
const {
quiz_session_id,
question_index,
question_type,
learning_style,
nivel,
answer,
is_correct,
response_time_ms
} = data;
const response = await fetch(`${this.baseURL}/quiz/response`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({
quiz_session_id,
question_index, // <-- IMPORTANTE: Antes era questionIndex
question_type,
learning_style,
nivel,
answer, // No hace falta stringify aquí si el backend ya lo maneja o si es JSONB directo
is_correct,
response_time_ms
})
});
// Nota: No puedes llamar a .text() y luego a .json() sobre la misma respuesta
if (!response.ok) {
const errData = await response.json().catch(() => ({ error: 'Error desconocido' }));
throw new Error(errData.error || 'Error al guardar respuesta del quiz');
}
return await response.json();
}
async saveQuizCompletion(score, totalTimeSeconds, learningStyle, suggestedLevel) {
const response = await fetch(`${this.baseURL}/quiz/complete`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({
score,
totalTimeSeconds,
learningStyle,
suggestedLevel
})
});
if (!response.ok) {
const errData = await response.json();
throw new Error(errData.error || 'Error al completar quiz');
}
return await response.json();
}
// Quiz Padres
// QUIZ PADRES
async saveParentQuizResponse(questionIndex, section, answer) {
const response = await fetch(`${this.baseURL}/parent-quiz/response`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({ questionIndex, section, answer })
});
if (!response.ok) throw new Error('Error al guardar respuesta del quiz de padres');
return await response.json();
}
async getParentQuizProgress() {
const response = await fetch(`${this.baseURL}/parent-quiz/progress`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Error al obtener progreso del quiz de padres');
const data = await response.json();
return data.progress;
}
async completeParentQuiz(communicationScore, learningStyle) {
const response = await fetch(`${this.baseURL}/parent-quiz/complete`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({ communicationScore, learningStyle })
});
if (!response.ok) throw new Error('Error al completar quiz de padres');
return await response.json();
}
async needsOnboardingCheck() {
try {
const user = this.getCurrentUser();
if (!user) return false;
// Si ya sabemos que faltan datos del storage
if (!user.birth || !user.country) return true;
// Opcional: consulta al backend para datos frescos (más seguro)
const response = await fetch(`${this.baseURL}/user/profile`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Error al verificar perfil');
const profile = await response.json();
return !profile.birth || !profile.country;
} catch (error) {
console.error('Error checking onboarding:', error);
return false; // Si falla, deja pasar (mejor no bloquear)
}
}
async loginWithGoogle(googleCredential) {
const response = await fetch(`${this.baseURL}/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: googleCredential })
});
return this._handleAuthResponse(response);
}
/**
* Core logic to process authentication responses and persist session.
* @private
*/
async _handleAuthResponse(response) {
const data = await response.json();
// Improved error handling: capture backend error messages precisely
if (!response.ok) {
const errorMsg = data.error || `Error ${response.status}: Authentication Failed`;
throw new Error(errorMsg);
}
this.currentUser = data.user;
this.token = data.token;
// Persist session to LocalStorage
localStorage.setItem('blueminds_current_user', JSON.stringify(data.user));
localStorage.setItem('blueminds_token', data.token);
return data;
}
logout() {
this.currentUser = null;
this.token = null;
localStorage.clear();
window.location.href = '/login.html';
}
// ========================================================================
// GAME PROGRESS MODULE
// ========================================================================
async getGameProgress(userId) {
try {
const response = await fetch(`${this.baseURL}/progress/${userId}`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Failed to fetch progress');
return await response.json();
} catch (error) {
console.error('[API Error]:', error);
return [];
}
}
async getGameProgressById(userId, gameId) {
try {
const response = await fetch(`${this.baseURL}/progress/${userId}/${gameId}`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Failed to fetch specific game progress');
return await response.json();
} catch (error) {
console.error('[API Error]:', error);
return null;
}
}
async updateGameProgress(userId, gameId, gameTitle, score, level, maxLevel, completionPercentage, timePlayed = 0) {
const response = await fetch(`${this.baseURL}/progress/update`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({
userId, gameId, gameTitle,
score: parseInt(score),
level: parseInt(level),
maxLevel: parseInt(maxLevel),
completionPercentage: parseFloat(completionPercentage),
timePlayed: parseInt(timePlayed)
})
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Failed to update progress');
return data;
}
// ========================================================================
// THERAPY SESSIONS MODULE
// ========================================================================
async saveTherapySession(userId, gameId, duration, performance, notes = '') {
const response = await fetch(`${this.baseURL}/therapy-session`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({
userId, gameId,
duration: parseInt(duration),
performance, notes
})
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Failed to save therapy session');
return data;
}
async getTherapySessions(userId) {
try {
const response = await fetch(`${this.baseURL}/therapy-sessions/${userId}`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Failed to fetch therapy sessions');
return await response.json();
} catch (error) {
console.error('[API Error]:', error);
return [];
}
}
async completeProfile(birth, country) {
const response = await fetch(`${this.baseURL}/user/complete-profile`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({ birth, country })
});
return this._handleAuthResponse(response); // Reutilizamos la misma función
}
// ========================================================================
// ANALYTICS & SYSTEM
// ========================================================================
async getUserStats(userId) {
try {
const response = await fetch(`${this.baseURL}/stats/${userId}`, {
headers: this._getHeaders()
});
if (!response.ok) throw new Error('Failed to fetch statistics');
return await response.json();
} catch (error) {
console.error('[API Error]:', error);
return { totalGamesStarted: 0, totalGamesSessions: 0, totalTimeSpent: 0, averageCompletion: 0, maxCompletion: 0 };
}
}
async checkHealth() {
try {
const response = await fetch(`${this.baseURL}/health`);
return response.ok;
} catch { return false; }
}
getCurrentUser() { return this.currentUser; }
_loadUser() {
const stored = localStorage.getItem('blueminds_current_user');
return stored ? JSON.parse(stored) : null;
}
}
const api = new BlueMindsAPI();