mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-25 20:59:28 +00:00
fix: refactor two commands in saving grade to prevent race conditions
This commit is contained in:
@@ -192,13 +192,9 @@ export class DecksController {
|
||||
description: 'Save the grade of a card',
|
||||
summary: 'Save the grade of a card',
|
||||
})
|
||||
async saveGrade(@Param('id') deckId: string, @Req() req, @Body() body: SaveGradeDto) {
|
||||
const saved = await this.commandBus.execute(
|
||||
new SaveGradeCommand(req.user.id, { cardId: body.cardId, grade: body.grade })
|
||||
)
|
||||
|
||||
async saveGrade(@Req() req, @Body() body: SaveGradeDto) {
|
||||
return await this.commandBus.execute(
|
||||
new GetRandomCardInDeckCommand(req.user.id, saved.deckId, saved.id)
|
||||
new SaveGradeCommand(req.user.id, { cardId: body.cardId, grade: body.grade })
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ import { Deck } from '../entities/deck.entity'
|
||||
import { DecksRepository } from '../infrastructure/decks.repository'
|
||||
|
||||
export class CreateDeckCommand {
|
||||
constructor(public readonly deck: CreateDeckDto, public readonly cover: Express.Multer.File) {}
|
||||
constructor(
|
||||
public readonly deck: CreateDeckDto,
|
||||
public readonly cover: Express.Multer.File
|
||||
) {}
|
||||
}
|
||||
|
||||
@CommandHandler(CreateDeckCommand)
|
||||
|
||||
@@ -4,7 +4,10 @@ import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
|
||||
import { DecksRepository } from '../infrastructure/decks.repository'
|
||||
|
||||
export class DeleteDeckByIdCommand {
|
||||
constructor(public readonly id: string, public readonly userId: string) {}
|
||||
constructor(
|
||||
public readonly id: string,
|
||||
public readonly userId: string
|
||||
) {}
|
||||
}
|
||||
|
||||
@CommandHandler(DeleteDeckByIdCommand)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { ForbiddenException, Logger, NotFoundException } from '@nestjs/common'
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { pick } from 'remeda'
|
||||
|
||||
import { CardsRepository } from '../../cards/infrastructure/cards.repository'
|
||||
import { DecksRepository } from '../infrastructure/decks.repository'
|
||||
@@ -14,58 +12,15 @@ export class GetRandomCardInDeckCommand {
|
||||
) {}
|
||||
}
|
||||
|
||||
type CardWithGrade = Prisma.cardGetPayload<{ include: { grades: true } }>
|
||||
|
||||
@CommandHandler(GetRandomCardInDeckCommand)
|
||||
export class GetRandomCardInDeckHandler implements ICommandHandler<GetRandomCardInDeckCommand> {
|
||||
logger = new Logger(GetRandomCardInDeckHandler.name)
|
||||
|
||||
constructor(
|
||||
private readonly cardsRepository: CardsRepository,
|
||||
private readonly decksRepository: DecksRepository
|
||||
) {}
|
||||
|
||||
private async getSmartRandomCard(cards: Array<CardWithGrade>): Promise<CardWithGrade> {
|
||||
const selectionPool: Array<CardWithGrade> = []
|
||||
|
||||
cards.forEach(card => {
|
||||
// Calculate the average grade for the card
|
||||
const averageGrade =
|
||||
card.grades.length === 0
|
||||
? 0
|
||||
: card.grades.reduce((acc, grade) => acc + grade.grade, 0) / card.grades.length
|
||||
// Calculate weight for the card, higher weight for lower grade card
|
||||
const weight = 6 - averageGrade
|
||||
|
||||
// Add the card to the selection pool `weight` times
|
||||
for (let i = 0; i < weight; i++) {
|
||||
selectionPool.push(card)
|
||||
}
|
||||
})
|
||||
|
||||
return selectionPool[Math.floor(Math.random() * selectionPool.length)]
|
||||
}
|
||||
|
||||
private async getNotDuplicateRandomCard(
|
||||
cards: Array<CardWithGrade>,
|
||||
previousCardId: string
|
||||
): Promise<CardWithGrade> {
|
||||
const randomCard = await this.getSmartRandomCard(cards)
|
||||
|
||||
if (!randomCard) {
|
||||
this.logger.error(`No cards found in deck}`, {
|
||||
previousCardId,
|
||||
randomCard,
|
||||
cards,
|
||||
})
|
||||
throw new NotFoundException(`No cards found in deck`)
|
||||
}
|
||||
if (randomCard.id === previousCardId && cards.length !== 1) {
|
||||
return this.getNotDuplicateRandomCard(cards, previousCardId)
|
||||
}
|
||||
|
||||
return randomCard
|
||||
}
|
||||
|
||||
async execute(command: GetRandomCardInDeckCommand) {
|
||||
const deck = await this.decksRepository.findDeckById(command.deckId)
|
||||
|
||||
@@ -74,32 +29,11 @@ export class GetRandomCardInDeckHandler implements ICommandHandler<GetRandomCard
|
||||
if (deck.userId !== command.userId && deck.isPrivate) {
|
||||
throw new ForbiddenException(`You can't get a private deck that you don't own`)
|
||||
}
|
||||
const cards = await this.cardsRepository.findCardsByDeckIdWithGrade(
|
||||
|
||||
return await this.cardsRepository.getRandomCardInDeck(
|
||||
command.deckId,
|
||||
command.userId,
|
||||
command.deckId
|
||||
command.previousCardId
|
||||
)
|
||||
|
||||
if (!cards.length) {
|
||||
throw new NotFoundException(`No cards found in deck with id ${command.deckId}`)
|
||||
}
|
||||
|
||||
const smartRandomCard = await this.getNotDuplicateRandomCard(cards, command.previousCardId)
|
||||
|
||||
return {
|
||||
...pick(smartRandomCard, [
|
||||
'id',
|
||||
'question',
|
||||
'answer',
|
||||
'deckId',
|
||||
'questionImg',
|
||||
'answerImg',
|
||||
'questionVideo',
|
||||
'answerVideo',
|
||||
'created',
|
||||
'updated',
|
||||
'shots',
|
||||
]),
|
||||
grade: smartRandomCard.grades[0]?.grade || 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { ForbiddenException, NotFoundException } from '@nestjs/common'
|
||||
import {
|
||||
ForbiddenException,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common'
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
|
||||
|
||||
import { CardsRepository } from '../../cards/infrastructure/cards.repository'
|
||||
import { DecksRepository } from '../infrastructure/decks.repository'
|
||||
import { GradesRepository } from '../infrastructure/grades.repository'
|
||||
|
||||
@@ -16,9 +22,12 @@ export class SaveGradeCommand {
|
||||
|
||||
@CommandHandler(SaveGradeCommand)
|
||||
export class SaveGradeHandler implements ICommandHandler<SaveGradeCommand> {
|
||||
private readonly logger = new Logger(SaveGradeHandler.name)
|
||||
|
||||
constructor(
|
||||
private readonly decksRepository: DecksRepository,
|
||||
private readonly gradesRepository: GradesRepository
|
||||
private readonly gradesRepository: GradesRepository,
|
||||
private readonly cardsRepository: CardsRepository
|
||||
) {}
|
||||
|
||||
async execute(command: SaveGradeCommand) {
|
||||
@@ -28,14 +37,21 @@ export class SaveGradeHandler implements ICommandHandler<SaveGradeCommand> {
|
||||
throw new NotFoundException(`Deck containing card with id ${command.args.cardId} not found`)
|
||||
|
||||
if (deck.userId !== command.userId && deck.isPrivate) {
|
||||
throw new ForbiddenException(`You can't save cards to a private deck that you don't own`)
|
||||
throw new ForbiddenException(`You can't save cards to a private deck that you don't own`)
|
||||
}
|
||||
|
||||
return await this.gradesRepository.createGrade({
|
||||
userId: command.userId,
|
||||
grade: command.args.grade,
|
||||
cardId: command.args.cardId,
|
||||
deckId: deck.id,
|
||||
})
|
||||
try {
|
||||
await this.gradesRepository.createGrade({
|
||||
userId: command.userId,
|
||||
grade: command.args.grade,
|
||||
cardId: command.args.cardId,
|
||||
deckId: deck.id,
|
||||
})
|
||||
} catch (e) {
|
||||
this.logger.error(e)
|
||||
throw new InternalServerErrorException(e?.message)
|
||||
}
|
||||
|
||||
return this.cardsRepository.getRandomCardInDeck(deck.id, command.userId, command.args.cardId)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user