-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
88 lines (64 loc) · 2.09 KB
/
main.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
const Joi = require('joi'); //It returns class
const express = require('express'); //It returns object
const app = express();
app.use(express.json());
let books = [
{ id : 1, name: 'Angular'},
{ id : 2, name: 'Node'},
{ id : 3, name: 'Java'}
]
app.get('/', (req,res)=>{
res.send("Hello Developers!!!");
})
//GET
app.get('/api/books', (req, res)=>{
res.send(books)
})
//POST
app.post('/api/books', (req,res)=>{
const { error } = validateBook(req.body);
if(error) return res.status(400).send(error.details[0].message);
const book = {
id : books.length + 1,
name : req.body.name
}
books.push(book);
res.send(book);
})
//PUT
app.put('/api/books/:id', (req, res)=>{
let book = books.find(b => b.id === parseInt(req.params.id))
if(!book) return res.status(404).send("The Book with the given ID was not found.")
const { error } = validateBook(req.body);
if(error) return res.status(400).send(error.details[0].message);
book.name = req.body.name;
res.send(book);
})
//DELETE
app.delete('/api/books/:id', (req, res)=>{
let book = books.find(b => b.id === parseInt(req.params.id))
if(!book) return res.status(404).send("The Book with the given ID was not found.")
const index = books.indexOf(book);
books.splice(index, 1);
res.send(book);
})
function validateBook(book){
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(book, schema);
}
app.get('/api/books/:id', (req, res)=>{
let book = books.find(b => b.id === parseInt(req.params.id))
if(!book) return res.status(404).send("The Book with the given ID was not found.")
res.send(book)
})
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
console.log(`Listening on port ${port}...`);
})
// For Knowledge purpose
// Query String Parameters are used to provide additional data to our backends services(These are added in url after ? mmark)
// We use Route parameters for essential and required values and query string parameters for anything that is optional
//res.send(req.params)
//res.send(req.query)