-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcontroller.js
189 lines (164 loc) · 5.25 KB
/
controller.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
183
184
185
186
187
188
189
const BaseController = require('../../../framework/Controller.class')
const DB = require('../../../models')
const U = require('../../../utils')
const R = require('ramda')
const Sequelize = require('sequelize')
class QuizController extends BaseController {
constructor () {
super(...arguments)
new Array('handleSubmit', 'handleQueryById', 'handleQuery').forEach(fn => {
this[fn] = this[fn].bind(this)
})
}
async handleQuery(req, res) {
try {
let {rows, count} = await this.findAll(...arguments)
const includeModelNames = this.getIncludeModelNames(req)
const limit = this.generateLimitStatement(req)
const offset = this.generateOffsetStatement(req)
let quizQuestionCounts = await DB.quizzes.findAll({
includeIgnoreAttributes: false,
attributes: [ 'id' ,[Sequelize.fn('count', Sequelize.col('questions->quizQuestions.id')), 'total']],
include: {
model: DB.questions,
},
where: {
id: {
$in: rows.map(q => q.id)
}
},
raw: true,
group: ['quizzes.id']
})
quizQuestionCounts = R.groupBy(obj => obj.id)(quizQuestionCounts)
rows = rows.map( _ => _.get({plain: true}))
rows = rows.map(row => {
row.totalQuestions = quizQuestionCounts[row.id][0].total
return row
})
rows.pagination = {
count,
currentOffset: offset,
nextOffset: offset + limit < count ? offset + limit : count,
prevOffset: offset - limit > 0 ? offset - limit : 0,
}
const result = this.serialize(rows, includeModelNames)
res.json(result)
} catch (err) {
this.handleError(err, res)
}
}
async handleQueryById(req, res, next) {
try {
const row = await this.findById(...arguments)
const includeModelNames = this.getIncludeModelNames(req)
const data = row.get({plain: true})
const count = await DB.quizQuestions.count({
where: {
quizId: row.id
}
})
data.totalQuestions = count
res.json(this.serialize(data, includeModelNames))
} catch (err) {
this.handleError(err, res)
}
}
async handleUpdateById (req, res) {
const modelObj = await this.deserialize(req.body)
let questions = modelObj.questions || []
const quiz = await this._model.findById(req.params.id, {
include: DB.questions
})
const oldQuestions = quiz.questions.map(q => q.id)
questions = questions.map(q => +q)
const questionsToAdd = R.difference(questions, oldQuestions)
const questionToRemove = R.difference(oldQuestions, questions)
const addQuestions = quiz.addQuestions(questionsToAdd, {
through: {
updatedById: req.user.id
}
})
const removeQuestions = DB.quizQuestions.destroy({
where:{
quizId: quiz.id,
questionId: {
$in: questionToRemove
}
}
})
const setUpdatedBy = DB.quizQuestions.update({
updatedById: req.user.id
}, {
where: {
quizId: quiz.id
}
})
await Promise.all([addQuestions, removeQuestions, setUpdatedBy])
return super.handleUpdateById(...arguments)
}
// body : {
// questions: [{
// id: '',
// markedChoices: []
// }]
// }
async handleSubmit (req, res, next) {
let markedQuestions = req.body.questions
const quiz = await this._model.findById(req.params.id, {
include: {
model: DB.questions,
include: {
model: DB.choices,
attributes: ['id', 'title', 'positiveWeight', 'negativeWeight']
}
}
})
if (!Array.isArray(markedQuestions)) {
//user has not marked any choice
markedQuestions = []
}
const results = quiz.questions.map(question => {
const markedQuestion = markedQuestions.find(el => el.id == question.id)
if (!markedQuestion) {
//user marked no response for this question
return {
id: question.id,
score: 0,
correctlyAnswered: [],
incorrectlyAnswered: [],
answers: req.query.showAnswers ? question.correctAnswers : undefined
}
}
// we only interested in POJO
question = question.get({plain: true})
// parse the array as integer
const markedChoices = U.parseIntArray(markedQuestion.markedChoices)
// check if the markedChoice are contained in possibleChoices
const areMarkedChoiceValid = U.isContainedIn(markedChoices, question.choices.map(_ => _.id))
if(!areMarkedChoiceValid) {
res.status(400).json({
error: 'markedChoices are out of bounds'
})
return ;
}
const { score, correctlyAnswered, incorrectlyAnswered } = U.getScore(markedChoices, U.parseIntArray(question.correctAnswers), question.choices)
return {
id: markedQuestion.id,
score,
correctlyAnswered,
incorrectlyAnswered,
answers: req.query.showAnswers ? question.correctAnswers : undefined
}
})
if (!res.headersSent) {
res.json({
id: quiz.id,
type: 'quiz',
score: results.reduce((acc, val) => acc + val.score, 0),
questions: results
})
}
}
}
module.exports = QuizController