diff --git a/src/Quiz/quiz.schema.ts b/src/Quiz/quiz.schema.ts index 5c2c2fb..70a7ef5 100644 --- a/src/Quiz/quiz.schema.ts +++ b/src/Quiz/quiz.schema.ts @@ -1,10 +1,10 @@ +import crypto from 'crypto' import { Inject, Injectable } from '@nestjs/common' import { AnswerType, Role } from '@prisma/client' import { QuestionType } from '@prisma/client' import { Pothos, PothosRef, PothosSchema, SchemaBuilderToken } from '@smatch-corp/nestjs-pothos' import { Builder } from '../Graphql/graphql.builder' import { PrismaService } from '../Prisma/prisma.service' - @Injectable() export class QuizSchema extends PothosSchema { constructor( @@ -155,6 +155,10 @@ export class QuizSchema extends PothosSchema { type: 'String', required: false, }), + amount: t.arg({ + type: 'Int', + required: false, + }), }, resolve: async (query, _root, args, ctx, _info) => { if (ctx.isSubscription) { @@ -168,16 +172,23 @@ export class QuizSchema extends PothosSchema { const centerMentor = await this.prisma.centerMentor.findUnique({ where: { mentorId: ctx.http.me.id }, }) + // using pseudo random to get amount of quizzes based on userid as seed + const random = getRandomWithSeed( + parseInt(crypto.createHash('sha256').update(ctx.http.me.id).digest('hex'), 16), + ) if (!centerMentor) { throw new Error('Center mentor not found') } - return await this.prisma.quiz.findMany({ + const quizzes = await this.prisma.quiz.findMany({ ...query, where: { serviceId: args.serviceId, centerMentorId: centerMentor.mentorId, }, }) + // get amount of quizzes using args.amount and random index based on random + const randomIndex = Math.floor(random * quizzes.length) + return quizzes.slice(randomIndex, randomIndex + (args.amount ?? 1)) } // use case 2: Customer @@ -311,3 +322,12 @@ export class QuizSchema extends PothosSchema { })) } } + +function seededRandom(seed: number) { + const x = Math.sin(seed) * 10000 + return x - Math.floor(x) +} + +function getRandomWithSeed(seed: number) { + return seededRandom(seed) +}