trivia: implement logic that checks if the questions exists in the db already and if not then it fetches a new question

This commit is contained in:
Ayden Jahola 2024-09-06 02:27:50 +01:00
parent 99dc71fc60
commit 3efa8eac1b
No known key found for this signature in database
GPG key ID: 71DD90AE4AE92742

View file

@ -33,16 +33,13 @@ const fetchTriviaQuestion = async (categoryId, categoryName) => {
category: categoryName, category: categoryName,
}).sort({ last_served: 1 }); }).sort({ last_served: 1 });
// If no old question or API call interval has passed
if (!triviaQuestion || Date.now() - LAST_API_CALL.time >= API_INTERVAL) { if (!triviaQuestion || Date.now() - LAST_API_CALL.time >= API_INTERVAL) {
// Fetch a new question from the API
const response = await axios.get( const response = await axios.get(
`https://opentdb.com/api.php?amount=1&category=${categoryId}` `https://opentdb.com/api.php?amount=1&category=${categoryId}`
); );
triviaQuestion = response.data.results[0]; triviaQuestion = response.data.results[0];
LAST_API_CALL.time = Date.now(); LAST_API_CALL.time = Date.now();
// Save the new question to the database
await TriviaQuestion.create({ await TriviaQuestion.create({
question: decode(triviaQuestion.question), question: decode(triviaQuestion.question),
correct_answer: decode(triviaQuestion.correct_answer), correct_answer: decode(triviaQuestion.correct_answer),
@ -51,14 +48,12 @@ const fetchTriviaQuestion = async (categoryId, categoryName) => {
last_served: null, last_served: null,
}); });
// Fetch the newly created question
triviaQuestion = await TriviaQuestion.findOne({ triviaQuestion = await TriviaQuestion.findOne({
question: decode(triviaQuestion.question), question: decode(triviaQuestion.question),
category: categoryName, category: categoryName,
}); });
} }
// Update the last served timestamp
if (triviaQuestion) { if (triviaQuestion) {
triviaQuestion.last_served = new Date(); triviaQuestion.last_served = new Date();
await triviaQuestion.save(); await triviaQuestion.save();
@ -71,6 +66,29 @@ const fetchTriviaQuestion = async (categoryId, categoryName) => {
} }
}; };
const getShuffledQuestions = async (categoryName) => {
try {
const questions = await TriviaQuestion.find({
category: categoryName,
}).sort({ last_served: 1 });
if (questions.length === 0) {
return [];
}
questions.forEach(async (question) => {
question.last_served = new Date();
await question.save();
});
// Shuffle questions
return questions.sort(() => Math.random() - 0.5);
} catch (error) {
console.error("Error fetching or shuffling questions:", error);
throw new Error("Error fetching questions from database");
}
};
const createTriviaEmbed = ( const createTriviaEmbed = (
categoryName, categoryName,
question, question,
@ -224,10 +242,20 @@ module.exports = {
const categoryId = interaction.options.getString("category"); const categoryId = interaction.options.getString("category");
const categoryName = CATEGORY_MAP[categoryId] || "Video Games"; const categoryName = CATEGORY_MAP[categoryId] || "Video Games";
const triviaQuestion = await fetchTriviaQuestion( let triviaQuestion = await fetchTriviaQuestion(categoryId, categoryName);
categoryId,
categoryName if (!triviaQuestion) {
); // If all questions have been served, fetch questions from the database
const shuffledQuestions = await getShuffledQuestions(categoryName);
if (shuffledQuestions.length === 0) {
throw new Error("No questions available for this category.");
}
triviaQuestion = shuffledQuestions[0];
triviaQuestion.last_served = new Date();
await triviaQuestion.save();
}
if (!triviaQuestion) throw new Error("Failed to fetch trivia question"); if (!triviaQuestion) throw new Error("Failed to fetch trivia question");
const question = decode(triviaQuestion.question); const question = decode(triviaQuestion.question);