75 lines
2.8 KiB
JavaScript
75 lines
2.8 KiB
JavaScript
/**
|
|
* Mappers Kit
|
|
* Helper functions to transform data between Client App and Game Iframe
|
|
*/
|
|
export function prepareCompletedQuestions(answeredQuestions) {
|
|
return (answeredQuestions || []).map(a => ({
|
|
id: a.id || a.questionId,
|
|
result: (a.isCorrect || a.result === 1) ? 1 : 0,
|
|
}));
|
|
}
|
|
export function createGamePayload(options) {
|
|
const { gameId, userId, gameData, answeredQuestions = [], endTimeIso } = options;
|
|
const completed_question_ids = prepareCompletedQuestions(answeredQuestions);
|
|
// Ưu tiên lấy field .questions hoặc .data, hoặc dùng chính gameData nếu nó là mảng
|
|
let data = [];
|
|
if (Array.isArray(gameData)) {
|
|
data = gameData;
|
|
}
|
|
else if (gameData && Array.isArray(gameData.questions)) {
|
|
data = gameData.questions;
|
|
}
|
|
else if (gameData && Array.isArray(gameData.data)) {
|
|
data = gameData.data;
|
|
}
|
|
const payload = {
|
|
game_id: gameId,
|
|
user_id: userId,
|
|
data: data,
|
|
completed_question_ids: completed_question_ids,
|
|
// Merge các field metadata khác
|
|
...(typeof gameData === 'object' && !Array.isArray(gameData) ? gameData : {}),
|
|
// Merge extraData
|
|
...(options.extraData || {})
|
|
};
|
|
// Inject end_time_iso (absolute timestamp for accurate sync)
|
|
if (endTimeIso) {
|
|
payload.end_time_iso = endTimeIso;
|
|
}
|
|
return payload;
|
|
}
|
|
export function createLeaderboardPayload(apiData) {
|
|
const topPlayers = apiData.topPlayers || [];
|
|
const userRank = apiData.userRank || null;
|
|
return {
|
|
top_players: topPlayers.map((p) => ({
|
|
rank: p.rank,
|
|
name: p.name || p.studentName || p.user_id,
|
|
score: p.score ?? p.finalScore ?? 0,
|
|
student_id: p.studentId || p.userId,
|
|
time_spent: p.timeSpent ?? p.time_spent ?? 0,
|
|
completed_at: p.completedAt
|
|
})),
|
|
user_rank: userRank ? {
|
|
rank: userRank.rank,
|
|
name: userRank.name || userRank.studentName,
|
|
score: userRank.score ?? userRank.finalScore ?? 0,
|
|
student_id: userRank.studentId || userRank.userId,
|
|
time_spent: userRank.timeSpent ?? userRank.time_spent ?? 0,
|
|
completed_at: userRank.completedAt
|
|
} : null,
|
|
};
|
|
}
|
|
export function normalizeAnswerReport(data) {
|
|
// Simplified per user request
|
|
// Input: { question_id: "Q1", result: 1, choice: "2" }
|
|
return {
|
|
question_id: data.question_id || data.questionId || data.id,
|
|
choice: data.choice ?? data.selected_answer ?? data.selectedAnswer,
|
|
result: data.result ?? (data.is_correct ? 1 : 0),
|
|
is_correct: !!(data.result === 1 || data.is_correct === true),
|
|
time_spent: data.time_spent ?? 5,
|
|
is_timeout: !!data.is_timeout
|
|
};
|
|
}
|
|
//# sourceMappingURL=mappers.js.map
|