-
Notifications
You must be signed in to change notification settings - Fork 0
/
playSessions.js
182 lines (160 loc) · 5.36 KB
/
playSessions.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
const router = require("express").Router()
const { PlaySession, Boardgame, Player, User, Activity, Image } = require("../models")
const { auth } = require("../middleware/authorization")
router.get("/", auth, async (request, response) => {
const playsessions = await PlaySession.findAll({
attributes: ["id", "duration", "date"],
include: [
{
model: Boardgame,
attributes: ["id", "name"]
},
{
model: User,
as: "players",
attributes: ["id", "name"],
through: {
attributes: ["score"]
}
}
]
})
response.json(playsessions)
})
router.get("/:id", auth, async (request, response) => {
const playsession = await PlaySession.findByPk(request.params.id, {
attributes: { exclude: ["boardgameId"] },
include: [
{
model: Boardgame,
attributes: { exclude: ["dateAdded", "addedById"] }
},
{
model: User,
as: "players",
attributes: ["id", "name"],
through: {
attributes: ["score"]
}
},
{
model: Image,
include: {
model: User,
attributes: ["id", "name"]
}
}
]
})
if (playsession) {
response.json(playsession)
} else {
response.status(404).end()
}
})
const validatePlaysession = (body, user) => {
const hasFields = (
body.boardgameId !== undefined &&
body.duration !== undefined &&
body.players !== undefined
)
if (!hasFields) return false
try {
const hasInvalidPlayers = body.players.some((player) => player.id === undefined || player.score === undefined)
if (hasInvalidPlayers) return false
const userInPlayers = body.players.some((player) => player.id === user.id)
if (!userInPlayers) return false
} catch (e) {
return false
}
return true
}
const createActivity = async (playSession) => {
const winnerId = playSession.players.reduce((acc, player) =>
(player.player.score > acc.score ? { id: player.id, score: player.player.score } : acc),
{ id: -1, score: -1 }
).id
const winnerQuery = User.findByPk(winnerId, { attributes: ["name"] })
const bg = await Boardgame.findByPk(playSession.boardgameId, { attributes: ["id", "name"] })
const winner = await winnerQuery
let description = `${bg.name} was played`
if (winner) {
if (playSession.players.length > 1) {
description = `${winner.name} won in ${bg.name} with ${playSession.players.length - 1} other${playSession.players.length > 2 ? "s" : ""}`
} else {
description = `${winner.name} won in ${bg.name}`
}
}
return await Activity.create({
description: description,
link: `/playsessions/${playSession.id}`
})
}
router.post("/", auth, async (request, response) => {
const playSession = request.body
if (!validatePlaysession(playSession, request.user)) {
return response.status(400).json({ error: "Invalid playsession" })
}
const playSessionObject = {
boardgameId: playSession.boardgameId,
duration: playSession.duration,
date: playSession.date,
description: playSession.description
}
try {
const ps = await PlaySession.create(playSessionObject)
await Player.bulkCreate(playSession.players.map(player =>
({ userId: player.id, playSessionId: ps.id, score: player.score })
))
const result = await PlaySession.findByPk(ps.id, {
include: [
{
model: User, as: "players", attributes: ["id", "name"], through: { attributes: ["score"] }
},
{
model: Boardgame,
attributes: ["id", "name"]
}
]
})
const activity = await createActivity(result)
const responseJSON = {
playSession: result.toJSON(),
activity: activity.toJSON(),
}
return response.json(responseJSON)
} catch(error) {
console.log(error)
return response.status(400).json({ error })
}
})
router.delete("/:id", auth, async (request, response) => {
const id = Number(request.params.id)
if (!Number.isInteger(id)) {
return response.sendStatus(404)
}
const playSession = await PlaySession.findByPk(id, {
include: [
{
model: User,
as: "players",
attributes: ["id"],
through: {
attributes: ["score"]
}
}
]}
)
if (!playSession) {
return response.sendStatus(404)
}
const user = request.user
const isPlayer = await playSession.hasPlayer(user)
if (!isPlayer && !user.isAdmin) {
return response.status(401).json({ error: "Not authorized to delete this playsession" })
}
await Player.destroy({ where: { playSessionId: id }})
await playSession.destroy()
return response.status(200).json(playSession.toJSON())
})
module.exports = router