From f1f5918a659ce4512c8a671e20f35e2b91876d43 Mon Sep 17 00:00:00 2001 From: Ly Tuan Kiet Date: Mon, 9 Dec 2024 20:37:04 +0700 Subject: [PATCH] refactor: improve quiz retrieval logic in Quiz schema - Enhanced the quiz retrieval logic to ensure a valid random index is calculated based on the number of available quizzes, preventing potential errors when no quizzes are present. - Updated the logic to use 'nrOfQuestions' from the quiz object for slicing the quizzes array, ensuring consistent behavior in quiz selection. - Improved code clarity by refining comments related to the quiz selection process. --- src/Quiz/quiz.schema.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Quiz/quiz.schema.ts b/src/Quiz/quiz.schema.ts index 269487a..dc30086 100644 --- a/src/Quiz/quiz.schema.ts +++ b/src/Quiz/quiz.schema.ts @@ -1,5 +1,5 @@ import crypto from 'crypto' -import { Inject, Injectable } from '@nestjs/common' +import { Inject, Injectable, Logger } from '@nestjs/common' import { AnswerType, Role } from '@prisma/client' import { QuestionType } from '@prisma/client' import { Pothos, PothosRef, PothosSchema, SchemaBuilderToken } from '@smatch-corp/nestjs-pothos' @@ -195,8 +195,12 @@ export class QuizSchema extends PothosSchema { }, }) // get amount of questions using nrOfQuestions and random index based on random - const randomIndex = Math.floor(random * (quizzes[0]?.nrOfQuestions ?? 1)) - return quizzes.slice(randomIndex, randomIndex + (quizzes[0]?.nrOfQuestions ?? 1)) + const randomIndex = quizzes.length > 0 + ? Math.floor(random * quizzes.length) + : 0 + const nrOfQuestions = quizzes[0]?.nrOfQuestions ?? 1 + const result = quizzes.slice(randomIndex, randomIndex + nrOfQuestions) + return result } // use case 2: center mentor or center owner