Mise à jour automatique du solde d'un⋅e utilisateur⋅rice après création ou modification d'un objet MoneyUpdate
This commit is contained in:
parent
b44ffcd380
commit
c6da328023
@ -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<void> {
|
||||
// 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<typeof extendPrismaClient>
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient {}
|
||||
export class PrismaService extends ExtendedPrismaClient {}
|
||||
|
Loading…
Reference in New Issue
Block a user