forked from midudev/curso-node-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmovies.js
59 lines (43 loc) · 1.48 KB
/
movies.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
import { validateMovie, validatePartialMovie } from '../schemas/movies.js'
export class MovieController {
constructor ({ movieModel }) {
this.movieModel = movieModel
}
getAll = async (req, res) => {
const { genre } = req.query
const movies = await this.movieModel.getAll({ genre })
res.json(movies)
}
getById = async (req, res) => {
const { id } = req.params
const movie = await this.movieModel.getById({ id })
if (movie) return res.json(movie)
res.status(404).json({ message: 'Movie not found' })
}
create = async (req, res) => {
const result = validateMovie(req.body)
if (!result.success) {
// 422 Unprocessable Entity
return res.status(400).json({ error: JSON.parse(result.error.message) })
}
const newMovie = await this.movieModel.create({ input: result.data })
res.status(201).json(newMovie)
}
delete = async (req, res) => {
const { id } = req.params
const result = await this.movieModel.delete({ id })
if (result === false) {
return res.status(404).json({ message: 'Movie not found' })
}
return res.json({ message: 'Movie deleted' })
}
update = async (req, res) => {
const result = validatePartialMovie(req.body)
if (!result.success) {
return res.status(400).json({ error: JSON.parse(result.error.message) })
}
const { id } = req.params
const updatedMovie = await this.movieModel.update({ id, input: result.data })
return res.json(updatedMovie)
}
}