-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
116 lines (83 loc) · 2.54 KB
/
app.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const express = require('express')
const crypto = require('node:crypto')
const cors = require('cors')
const movies = require('./movies.json')
const { validateMovie, validatePartialMovie } = require('./schemas/movies.js')
const app = express()
app.disable('x-powered-by')
app.use(cors({
origin: (origin, callback) => {
const ACCEPTED_ORIGINS = [
'http://localhost:8080',
'https://movies.com'
]
if (ACCEPTED_ORIGINS.includes(origin) || !origin) {
return callback(null, true)
}
return callback(new Error('Not allowed by CORS'))
}
}))
// Usar middleware que obtiene el json en el body de la request.
app.use(express.json())
app.get('/', (req, res) => {
res.json({ message: 'Hola mundo' })
})
app.get('/movies', (req, res) => {
const { genre } = req.query
if (genre) {
const filteredMovies = movies.filter(
movie => movie.genre.some(g => g.toLowerCase() === genre.toLowerCase())
)
return res.json(filteredMovies)
}
res.json(movies)
})
app.get('/movies/:id', (req, res) => {
const { id } = req.params
const movie = movies.find(movie => movie.id === id)
if (movie) return res.json(movie)
res.status(404).json({ message: 'Movie not found' })
})
app.post('/movies', (req, res) => {
const result = validateMovie(req.body)
if (!result.success) {
// return res.status(400).json({ error: JSON.parse(result.error.message) })
return res.status(400).json(result.error.format())
}
const newMovie = {
id: crypto.randomUUID(), // uuid v4
...result.data
}
movies.push(newMovie)
res.status(201).json(newMovie)
})
app.patch('/movies/:id', (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 movieIndex = movies.findIndex(movie => movie.id === id)
if (movieIndex === -1) {
return res.status(404).json({ message: 'Movie not found' })
}
const updateMovie = {
...movies[movieIndex],
...result.data
}
movies[movieIndex] = updateMovie
res.json(updateMovie)
})
app.delete('/movies/:id', (req, res) => {
const { id } = req.params
const movieIndex = movies.findIndex((movie) => movie.id === id)
if (movieIndex === -1) {
return res.status(404).json({ message: 'Movie not found' })
}
movies.splice(movieIndex, 1)
return res.json({ message: 'Movie deleted' })
})
const PORT = process.env.PORT ?? 3000
app.listen(PORT, () => {
console.log(`server listning on port http://localhost:${PORT}`)
})