add smart random

This commit is contained in:
2023-07-14 14:54:47 +02:00
parent 68942e904f
commit b14fb39009
25 changed files with 509 additions and 104 deletions

View File

@@ -2,6 +2,8 @@ import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common
import { PrismaService } from '../../../prisma.service'
import { GetAllCardsInDeckDto } from '../dto/get-all-cards.dto'
import { CreateCardDto } from '../dto/create-card.dto'
import { Pagination } from '../../../infrastructure/common/pagination/pagination.service'
import { createPrismaOrderBy } from '../../../infrastructure/common/helpers/get-order-by-object'
@Injectable()
export class CardsRepository {
@@ -48,23 +50,56 @@ export class CardsRepository {
async findCardsByDeckId(
deckId: string,
{ answer = undefined, question = undefined, currentPage, itemsPerPage }: GetAllCardsInDeckDto
{
answer = undefined,
question = undefined,
currentPage,
itemsPerPage,
orderBy,
}: GetAllCardsInDeckDto
) {
try {
return await this.prisma.card.findMany({
const where = {
decks: {
id: deckId,
},
question: {
contains: question || undefined,
},
answer: {
contains: answer || undefined,
},
}
const result = await this.prisma.$transaction([
this.prisma.card.count({ where }),
this.prisma.card.findMany({
orderBy: createPrismaOrderBy(orderBy) || { updated: 'desc' },
where,
skip: (currentPage - 1) * itemsPerPage,
take: itemsPerPage,
}),
])
return Pagination.transformPaginationData(result, { currentPage, itemsPerPage })
} catch (e) {
this.logger.error(e?.message)
throw new InternalServerErrorException(e?.message)
}
}
async findCardsByDeckIdWithGrade(userId: string, deckId: string) {
try {
return this.prisma.card.findMany({
where: {
decks: {
id: deckId,
},
question: {
contains: question || undefined,
},
answer: {
contains: answer || undefined,
deckId,
},
include: {
grades: {
where: {
userId,
deckId,
},
},
},
skip: (currentPage - 1) * itemsPerPage,
take: itemsPerPage,
})
} catch (e) {
this.logger.error(e?.message)
@@ -72,9 +107,9 @@ export class CardsRepository {
}
}
public async findDeckById(id: string) {
public async findCardById(id: string) {
try {
return await this.prisma.deck.findUnique({
return await this.prisma.card.findUnique({
where: {
id,
},
@@ -85,12 +120,25 @@ export class CardsRepository {
}
}
public async deleteDeckById(id: string) {
public async deleteCardById(id: string) {
try {
return await this.prisma.deck.delete({
where: {
id,
},
return await this.prisma.$transaction(async tx => {
const deleted = await tx.card.delete({
where: {
id,
},
})
await tx.deck.update({
where: {
id: deleted.deckId,
},
data: {
cardsCount: {
decrement: 1,
},
},
})
return deleted
})
} catch (e) {
this.logger.error(e?.message)