From 896b489498b8e61c1964616a09461e96fbf79187 Mon Sep 17 00:00:00 2001 From: Marco Escaleira Date: Mon, 15 Apr 2024 20:58:43 +0100 Subject: [PATCH] feat: generate quiz of the day with static variables --- schema.graphql | 3 +++ src/resolvers/quiz.resolver.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/schema.graphql b/schema.graphql index b08ec34..ac64ea0 100644 --- a/schema.graphql +++ b/schema.graphql @@ -196,6 +196,9 @@ type Query { """Get the list of all quizzes based on multiple filter.""" quizList(country: String, status: QuizStatus): [QuizData!]! + + """Get the quiz of the day""" + quizOfTheDay: QuizData! quizRating(quizId: String!): Int! """Get the list of all quizzes based on the country""" diff --git a/src/resolvers/quiz.resolver.ts b/src/resolvers/quiz.resolver.ts index f3e6cd2..5eed1e1 100644 --- a/src/resolvers/quiz.resolver.ts +++ b/src/resolvers/quiz.resolver.ts @@ -1,3 +1,4 @@ +import { differenceInCalendarDays } from 'date-fns'; import { Arg, Authorized, Ctx, Mutation, Query, registerEnumType, Resolver } from 'type-graphql'; import AttemptModel from '../models/attempt.model'; import QuizModel from '../models/quiz.model'; @@ -120,4 +121,32 @@ export default class QuizResolver { errorHandler(error); } } + + lastGeneratedQuiz: Date | undefined = undefined; + currentQuizOfDayId: any = undefined; + + @Query(() => QuizData, { description: 'Get the quiz of the day' }) + async quizOfTheDay() { + try { + // Generate the quiz of today if it's the first time + if (!this.lastGeneratedQuiz || !this.currentQuizOfDayId) { + const quizzes = await QuizModel.find(); + + this.lastGeneratedQuiz = new Date(); + this.currentQuizOfDayId = quizzes[Math.floor(Math.random() * quizzes.length)]; + } + + // Generate the quiz of today + if (differenceInCalendarDays(new Date(), this.lastGeneratedQuiz) >= 1) { + const quizzes = await QuizModel.find(); + + this.lastGeneratedQuiz = new Date(); + this.currentQuizOfDayId = quizzes[Math.floor(Math.random() * quizzes.length)]; + } + + return this.currentQuizOfDayId; + } catch (error) { + errorHandler(error); + } + } }