quiz.controller.js 1.62 KB
Newer Older
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
1
2
import formidable from 'formidable'
import fs from 'fs'
Yoon, Daeki's avatar
Yoon, Daeki committed
3
4
import Problem from './problem.model.js'
import Quiz from './quiz.model.js'
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
5
6

const create = async (req, res) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
7
8
9
10
11
12
13
14
15
16
17
18
  try {
    const { problems } = req.body

    const quiz = new Quiz()
    // console.log('quiz in quiz.controller:', quiz);

    for await (let problem of problems) {
      // console.log('problem in quiz.controller:', problem);
      const p = new Problem(problem)
      // console.log('problem in quiz.controller:', p);
      await p.save()
      quiz.problems.push(p._id)
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
19
20
21
22
    }

    quiz.author = req.profile

Yoon, Daeki's avatar
Yoon, Daeki committed
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
    // console.log('quiz in quiz.controller:', quiz);
    await quiz.save()
    quiz.author.hashedPassword = undefined
    quiz.author.salt = undefined
    res.json(quiz)
  } catch (error) {
    return res.status(400).json({
      error: 'Quiz save DB error' + error
    })
  }
}

const isAuthor = (req, res, next) => {
  const isAuthor = req.auth && req.quiz && req.auth._id == req.quiz.author._id
  if (!isAuthor) {
    return res.status(403).json({
      error: 'User is not an author'
    })
  }
  next()
}

const read = async (req, res) => {
  let quiz = req.quiz
  res.json(quiz)
}

const quizById = async (req, res, next, id) => {
  try {
    const quiz = await Quiz.findById(id)
      .populate('author', '_id name')
      .populate('problems')
      .exec()
    if (!quiz) {
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
57
      return res.status(400).json({
Yoon, Daeki's avatar
Yoon, Daeki committed
58
        error: 'Quiz not found'
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
59
60
      })
    }
Yoon, Daeki's avatar
Yoon, Daeki committed
61
62
63
64
65
66
67
    req.quiz = quiz
    next()
  } catch (error) {
    return res.status(400).json({
      error: 'Quiz by id query db error: ' + error
    })
  }
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
68
69
70
71
}

export default {
  create,
Yoon, Daeki's avatar
Yoon, Daeki committed
72
73
74
  read,
  isAuthor,
  quizById,
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
75
}