82 lines
3.1 KiB
JavaScript
82 lines
3.1 KiB
JavaScript
/**
|
|
* Game API Client Kit
|
|
* Standardized API client for communicating with Game Backend
|
|
*/
|
|
export class GameApiClient {
|
|
constructor(config) {
|
|
this.config = config;
|
|
}
|
|
async request(method, endpoint, body) {
|
|
const url = `${this.config.baseUrl}${endpoint}`;
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
...(this.config.getHeaders ? this.config.getHeaders() : {})
|
|
};
|
|
try {
|
|
const res = await fetch(url, {
|
|
method,
|
|
headers,
|
|
body: body ? JSON.stringify(body) : undefined
|
|
});
|
|
if (!res.ok) {
|
|
const errorBody = await res.text();
|
|
let errorMessage = `API Error ${res.status}: ${res.statusText}`;
|
|
let errorCode;
|
|
try {
|
|
const jsonError = JSON.parse(errorBody);
|
|
// Capture error code from response
|
|
if (jsonError.code !== undefined) {
|
|
errorCode = jsonError.code;
|
|
}
|
|
if (jsonError.message)
|
|
errorMessage += ` - ${jsonError.message}`;
|
|
else if (jsonError.error)
|
|
errorMessage += ` - ${jsonError.error}`;
|
|
}
|
|
catch (e) {
|
|
if (errorBody && errorBody.length < 200)
|
|
errorMessage += ` - ${errorBody}`;
|
|
}
|
|
// Throw error object with code and message
|
|
const error = new Error(errorMessage);
|
|
error.code = errorCode;
|
|
error.httpStatus = res.status;
|
|
throw error;
|
|
}
|
|
return await res.json();
|
|
}
|
|
catch (error) {
|
|
console.error('[GameApiClient] Request failed:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
async getGameWithProgress(assignmentId, studentId, refresh = false) {
|
|
return this.request('GET', `/submissions/live/init/${assignmentId}/${studentId}${refresh ? '?refresh=1' : ''}`);
|
|
}
|
|
async startLiveSession(assignmentId, studentId, refresh = false) {
|
|
return this.request('POST', `/submissions/live/start${refresh ? '?refresh=1' : ''}`, {
|
|
assignment_id: assignmentId,
|
|
student_id: studentId
|
|
});
|
|
}
|
|
async submitAnswer(assignmentId, studentId, questionId, answer, timeSpent = 5, isTimeout = false) {
|
|
return this.request('POST', '/submissions/live/answer', {
|
|
assignment_id: assignmentId,
|
|
student_id: studentId,
|
|
question_id: questionId,
|
|
selected_answer: answer,
|
|
time_spent: timeSpent,
|
|
is_timeout: isTimeout
|
|
});
|
|
}
|
|
async completeSession(assignmentId, studentId) {
|
|
return this.request('POST', '/submissions/live/complete', {
|
|
assignment_id: assignmentId,
|
|
student_id: studentId
|
|
});
|
|
}
|
|
async getLeaderboard(assignmentId, studentId) {
|
|
return this.request('GET', `/submissions/leaderboard/${assignmentId}?student_id=${studentId}`);
|
|
}
|
|
}
|
|
//# sourceMappingURL=api.js.map
|