-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (53 loc) · 1.81 KB
/
index.js
File metadata and controls
73 lines (53 loc) · 1.81 KB
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
const Joi =require('joi');
const express = require('express');
const app = express();
app.use(express.json()); //set req.body property
const movies = [
{ id:1, genre:'action'},
{ id:2, genre:'thriller'},
{ id:3, genre:'drama'},
{ id:4, genre:'horror'},
];
app.get('/api/movies',(req, res)=> {
res.send(movies);
});
app.get('/api/movies/:id', (req,res)=> {
// Get user with a given id
const movie = movies.find(m => m.id === parseInt(req.params.id));
if(!movie) return res.status(404).send('The movie with the given id not found');
res.send(movie);
});
app.post('/api/movies',(req,res)=>{
const {error} = validateMovies(req.body);
if(error) return res.status(400).send(error.details[0].message);
const movie = {
id : movies.length +1,
genre:req.body.genre
}
movies.push(movie);
res.send(movie);
});
app.put('/api/movies/:id',(req,res)=> {
const movie = movies.find(m => m.id === parseInt(req.params.id));
if(!movie) return res.status(404).send('The movie with the given id not found');
const {error} = validateMovies(req.body);
if(error) return res.status(400).send(error.details[0].message);
movie.genre =req.body.genre;
res.send(movie);
});
app.delete('/api/movies/:id',(req,res)=> {
const movie = movies.find(m => m.id === parseInt(req.params.id));
if(!movie) return res.status(404).send('The movie with the given id not found');
// Delete movie
const index = movies.indexOf(movie);
movies.slice(index,1); // Remove one object
res.send(movie);
});
function validateMovies(movie){
const schema = {
genre:Joi.string().min(3).required()
};
return Joi.validate(movie,schema);
}
const port = process.env.PORT || 3000;
app.listen(port, ()=> console.log(`Listening on port ${port}...`));