-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
47 lines (43 loc) · 1.22 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const { PrismaClient } = require('@prisma/client')
const { realtorAverageRating } = require('./services/metadata.service')
const { hashPassword } = require('./utils/password')
const prisma = new PrismaClient()
module.exports = prisma
/**
* @description middleware to initialize db and auto hash password on create requests on the user model
* also calculates average ratings for realtors whenever a new review is created.
*/
async function main () {
prisma.$use(async (params, next) => {
if (params.model === 'User') {
if (params.action === 'create') {
params.args.data.password = await hashPassword(
params.args.data.password
)
}
}
if (params.model === 'Review') {
if (params.action === 'create') {
const averageRating = await prisma.review.aggregate({
_avg: {
rating: true
},
where: {
realtorsId: params.args.data.realtorsId
}
}
)
await prisma.realtors.update({
where: {
id: params.args.data.realtorsId
},
data: {
averageRating: averageRating._avg.rating || 0
}
})
}
}
return next(params)
})
}
main()