import formidable from 'formidable' import fs from 'fs' import Problem from './problem.model.js' import Quiz from './quiz.model.js' const create = async (req, res) => { 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) } quiz.author = req.profile // 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) { return res.status(400).json({ error: 'Quiz not found' }) } req.quiz = quiz next() } catch (error) { return res.status(400).json({ error: 'Quiz by id query db error: ' + error }) } } export default { create, read, isAuthor, quizById, }