quiz.controller.js 792 Bytes
Newer Older
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
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
import formidable from 'formidable'
import fs from 'fs'
import quizModel from './quiz.model.js'

const create = async (req, res) => {
  const form = new formidable.IncomingForm()
  form.keepExtensions = true
  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.status(400).json({
        error: 'Image could not be uploaded'
      })
    }

    const quiz = new quizModel(fields)
    quiz.author = req.profile
    if (files.image) {
      quiz.image.data = fs.readFileSync(files.image.path)
      quiz.image.contentType = files.image.type
    }

    try {
      const result = await quiz.save()
      res.json(result)
    } catch (error) {
      return res.status(400).json({
        error: 'Quiz save db error'
      })
    }
  })
}

export default {
  create,
}