diff --git a/server/src/prisma/prisma.service.ts b/server/src/prisma/prisma.service.ts index a18770c..1834b3e 100644 --- a/server/src/prisma/prisma.service.ts +++ b/server/src/prisma/prisma.service.ts @@ -1,5 +1,57 @@ import { Injectable } from '@nestjs/common' -import { PrismaClient } from '@prisma/client' +import { PrismaClient, } from '@prisma/client' + +async function updateUserMoney(prisma: PrismaClient): Promise { + // On calcule le solde par utilisateur⋅rice pour mettre à jour l'objet User + const moneyPerUser = await prisma.moneyUpdate.groupBy({ + by: 'userId', + _sum: { + amount: true, + } + }) + for (const { userId, _sum } of moneyPerUser) { + const { amount } = _sum + await prisma.user.update({ + where: { + id: userId, + }, + data: { + money: amount + } + }) + } + // On réinitialise le solde s'il n'y a plus aucun MoneyUpdate + await prisma.user.updateMany({ + where: { + moneyUpdates: { none: {} } + }, + data: { + money: 0 + }, + }) +} + +function extendPrismaClient() { + const prisma = new PrismaClient() + return prisma.$extends({ + query: { + moneyUpdate: { + $allOperations({ model, operation, args, query }) { + const result = query(args) + if (!operation.startsWith("find") && !['aggregate', 'count', 'groupBy'].includes(operation)) + result.then(() => updateUserMoney(prisma)) + return result + } + } + } + }) +} + +const ExtendedPrismaClient = class { + constructor() { + return extendPrismaClient() + } +} as new () => ReturnType @Injectable() -export class PrismaService extends PrismaClient {} +export class PrismaService extends ExtendedPrismaClient {}