-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
69 lines (53 loc) · 1.55 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
const express = require("express")
const app = express()
const Joi = require("joi")
app.use(express.json())
const genres = [
{ id: 1, name: "Action" },
{ id: 2, name: "Sci-Fi" },
{ id: 3, name: "Comedy" },
{ id: 4, name: "Romance" },
{ id: 5, name: "Horror" },
]
app.get("/", (req, res) => {
res.send("Welcome to Videx, the best video rental service")
})
app.get("/api/genres", (req, res) => {
res.send(genres)
})
app.get("/api/genres/:id", (req, res) => {
res.send(genres[req.params.id - 1])
})
app.post("/api/genres", (req, res) => {
const newGenres = {
id: genres.length + 1,
name: req.body.name,
}
genres.push(newGenres)
res.send(genres)
})
app.put("/api/genres/:id", (req, res) => {
const genre = genres.find((c) => c.id === parseInt(req.params.id))
if (!genre)
return res.status(404).send("The genre with the given ID was not found.")
const { error } = validateGenre(req.body)
if (error) return res.status(400).send(error.details[0].message)
genre.name = req.body.name
res.send(genre)
})
app.delete("/api/genres/:id", (req, res) => {
const genre = genres.find((c) => c.id === parseInt(req.params.id))
if (!genre)
return res.status(404).send("The genre with the given ID was not found.")
const index = genres.indexOf(genre)
genres.splice(index, 1)
res.send(genres)
})
function validateGenre(genre) {
const schema = {
name: Joi.string().min(3).required(),
}
return Joi.validate(genre, schema)
}
const port = 3000 || process.env.PORT
app.listen(port, () => console.log(`listening on port ${port}`))