From eb6445b0f910ae2bc5e0adcc65d1d15c382169f2 Mon Sep 17 00:00:00 2001 From: Ayden Jahola Date: Sun, 8 Sep 2024 18:38:08 +0100 Subject: [PATCH] trivia: avoid adding duplicate questiosn to the db --- commands/games/trivia.js | 46 ++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/commands/games/trivia.js b/commands/games/trivia.js index 8672b89..ad16c1d 100644 --- a/commands/games/trivia.js +++ b/commands/games/trivia.js @@ -100,31 +100,45 @@ const fetchTriviaQuestion = async (categoryId, categoryName) => { `https://opentdb.com/api.php?amount=1&category=${categoryId}&token=${sessionToken}` ); const retryApiQuestion = retryResponse.data.results[0]; - await TriviaQuestion.create({ - question: decode(retryApiQuestion.question), - correct_answer: decode(retryApiQuestion.correct_answer), - incorrect_answers: retryApiQuestion.incorrect_answers.map(decode), - category: categoryName, - last_served: null, - }); - triviaQuestion = await TriviaQuestion.findOne({ question: decode(retryApiQuestion.question), category: categoryName, }); + + if (!triviaQuestion) { + await TriviaQuestion.create({ + question: decode(retryApiQuestion.question), + correct_answer: decode(retryApiQuestion.correct_answer), + incorrect_answers: retryApiQuestion.incorrect_answers.map(decode), + category: categoryName, + last_served: null, + }); + + triviaQuestion = await TriviaQuestion.findOne({ + question: decode(retryApiQuestion.question), + category: categoryName, + }); + } } else { - await TriviaQuestion.create({ - question: decode(apiQuestion.question), - correct_answer: decode(apiQuestion.correct_answer), - incorrect_answers: apiQuestion.incorrect_answers.map(decode), - category: categoryName, - last_served: null, - }); - triviaQuestion = await TriviaQuestion.findOne({ question: decode(apiQuestion.question), category: categoryName, }); + + if (!triviaQuestion) { + await TriviaQuestion.create({ + question: decode(apiQuestion.question), + correct_answer: decode(apiQuestion.correct_answer), + incorrect_answers: apiQuestion.incorrect_answers.map(decode), + category: categoryName, + last_served: null, + }); + + triviaQuestion = await TriviaQuestion.findOne({ + question: decode(apiQuestion.question), + category: categoryName, + }); + } } LAST_API_CALL.time = Date.now(); // Update the last API call time