course.controller.js 1.1 KB
Newer Older
Yoon, Daeki's avatar
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
import dbErrorHandler from "../helpers/dbErrorHandler.js"
import Course from "./course.model.js"

const create = async (req, res) => {
  try {
    const course = new Course(req.body)
    await course.save()
    return res.json(course)
  } catch (error) {
    return res.status(400).json({
      error: dbErrorHandler.getErrorMessage(error)
    })
  }
}

const list = async (req, res) => {
  try {
    const courses = await Course.find({}).exec()
    return res.json(courses)
  } catch (error) {
    return res.status(400).json({
      error: dbErrorHandler.getErrorMessage(error)
    })
  }
Yoon, Daeki's avatar
Yoon, Daeki committed
25
26
27
28
29
}

const read = (req, res) => {
  return res.json(req.course)
}
Yoon, Daeki's avatar
Yoon, Daeki committed
30

Yoon, Daeki's avatar
Yoon, Daeki committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const courseById = async (req, res, next, id) => {
  // console.log('req.body in userById', req.body);
  try {
    let course = await Course.findById(id)
      .exec()
    if (!course) {
      return res.status(400).json({
        error: 'Course not found'
      })
    }
    req.course = course
    next()
  } catch (error) {
    return res.status(400).json({
      error: 'Could not retrieve course'
    })
  }
Yoon, Daeki's avatar
Yoon, Daeki committed
48
49
50
51
52
}

export default {
  create,
  list,
Yoon, Daeki's avatar
Yoon, Daeki committed
53
54
  read,
  courseById,
Yoon, Daeki's avatar
Yoon, Daeki committed
55
}