-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
76 lines (57 loc) · 1.91 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
//add the dependencies
const Joi = require('joi');
const Express = require('express');
const app = Express();
//parse as JSON
app.use(Express.json());
const books = [
{id: 1, title: 'Unit1', author: 'myfriend1'},
{id: 2, title: 'Unit2', author: 'myfriend2'},
{id: 3, title: 'Unit3', author: 'myfriend3'},
{id: 4, title: 'Unit4', author: 'myfriend4'}
]
//HTTP get
app.get('/api/books', (req,res) => {
res.send(books);
});
app.get('/api/books/:title', (req,res) =>{
const book = books.find(b => b.title === req.params.title);
if(!book)
return res.status(404).send(`The book title "${req.params.title}" could not be found`);
res.send(book);
});
//HTTP post
app.post('/api/books', (req,res) =>{
const { error } = validateInput(req.body);
if( error ) return res.status(400).send(error.details[0].message);
const book = {
title: req.body.title
};
books.push(book);
res.send(book);
});
//HTTP put
app.put('/api/books/:title', (req,res) =>{
const book = books.find(b => b.title === parseInt(req.params.title));
if(!book) return res.status(404).send(`The book with title ${b.title} could not be found`);
const { error } = validateInput(req.body);
if( error ) return res.status(400).send(error.details[0].message);
book.title = req.body.title;
res.send(book);
})
//HTTP delete
app.delete('/api/books/:title', (req,res) =>{
const book = books.find(b => b.title === parseInt(req.params.title));
if(!book) return res.status(404).send(`The book with title ${b.title} could not be found`);
const index = books.indexOf(book);
books.splice(index, 1);
res.send(books);
});
function validateInput(course){
const schema = {
title: Joi.string().min(1).max(30).required
}
return Joi.validate(course, schema);
}
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening to port ${port}`));