-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathratings.js
More file actions
117 lines (109 loc) · 2.96 KB
/
ratings.js
File metadata and controls
117 lines (109 loc) · 2.96 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const db = require('./db')
const events = require('./events')
const npmNodes = require('./nodes')
async function saveRating (thingId, user, rating) {
await db.ratings.updateOne(
{
module: thingId,
user
},
{
$set: {
module: thingId,
user,
rating,
time: new Date()
}
},
{ upsert: true }
)
}
async function removeRating (thingId, user) {
await db.ratings.deleteOne({
module: thingId,
user
})
}
async function getModuleRating (npmModule) {
const results = await db.ratings.aggregate(
[
{ $match: { module: npmModule } },
{
$group: { _id: '$module', total: { $sum: '$rating' }, count: { $sum: 1 } }
}
]
).toArray()
console.log(results)
if (results.length > 0) {
return {
module: npmModule,
total: results[0].total,
count: results[0].count
}
}
}
async function getForUser (npmModule, user) {
return await db.ratings.findOne({
user,
module: npmModule
})
}
async function removeForModule (npmModule) {
return db.ratings.deleteOne({ module: npmModule })
}
async function getRatedModules () {
return db.ratings.distinct('module', {})
}
async function rateThing (thingId, userId, rating) {
try {
rating = Number(rating)
if (isNaN(rating) || rating === 0) {
await removeRating(thingId, userId)
await events.add({
action: 'module_rating',
module: thingId,
message: 'removed',
user: userId
})
} else {
await saveRating(thingId, userId, rating)
await events.add({
action: 'module_rating',
module: thingId,
message: rating,
user: userId
})
}
const currentRating = await module.exports.get(thingId)
let nodeRating = {}
if (currentRating && currentRating.count > 0) {
nodeRating = {
score: currentRating.total / currentRating.count,
count: currentRating.count
}
}
return npmNodes.update(thingId, { rating: nodeRating })
} catch (err) {
console.log('error rating node module: ' + thingId, err)
}
}
module.exports = {
rateThing,
get: async function (thingId, user) {
console.log('rate get', thingId, user)
let rating = null
const totalRatings = await getModuleRating(thingId)
if (!totalRatings) {
return null
}
rating = totalRatings
const userRating = await getForUser(thingId, user)
if (userRating) {
rating.userRating = userRating
}
return rating
},
getUserRating: getForUser,
getRatedModules,
removeForModule
}