From c6da3280230729cf5c5caa8aeda89cb9d5f5cef1 Mon Sep 17 00:00:00 2001 From: Emmy D'Anello Date: Sun, 8 Dec 2024 13:05:07 +0100 Subject: [PATCH] =?UTF-8?q?Mise=20=C3=A0=20jour=20automatique=20du=20solde?= =?UTF-8?q?=20d'un=E2=8B=85e=20utilisateur=E2=8B=85rice=20apr=C3=A8s=20cr?= =?UTF-8?q?=C3=A9ation=20ou=20modification=20d'un=20objet=20MoneyUpdate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/src/prisma/prisma.service.ts | 56 +++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) 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 {}