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.
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user