-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (84 loc) · 2.37 KB
/
index.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
const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{id:1,name:'course1'},
{id:2,name:'course2'},
{id:3,name:'course3'},
{id:4,name:'course4'}
];
//GET
app.get('/api/courses',(req,res)=>{
res.send(courses);
});
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c=>c.id === parseInt(req.params.id));
if(!course) return res.status(404).send('Course with given id not found.');
res.send(course);
});
//POST
/**
* @description manually handeling validations
*/
// app.post('/api/courses/', (req, res) => {
// if(!req.body.name || req.body.name.length < 3) {
// return res.status(400).send("name is required and length should be >=3");
// }
// const course = {
// id:courses.length+1,
// name:req.body.name
// }
// courses.push(course);
// res.send(course);
// });
/**
* @description handeling validations using 'Joi'
*/
app.post('/api/courses/', (req, res) => {
const { error } = validateCourse(req.body);
if(error){
return res.status(400).send(error.details[0].message);
}
const course = {
id: courses.length + 1,
name: req.body.name
}
courses.push(course);
res.send(course);
});
//PUT
app.put('/api/courses/:id', (req, res) => {
const course = courses.find(c=>c.id === parseInt(req.params.id));
if(!course) return res.status(404).send('Course with given id not found.');
const { error } = validateCourse(req.body);
if(error){
return res.status(400).send(error.details[0].message);
}
course.name = req.body.name;
res.send(course);
});
//DELETE
app.delete('/api/courses/:id', (req, res) => {
//Look up for the course in db
const course = courses.find(c=>c.id === parseInt(req.params.id));
if(!course) return res.status(404).send('Course with given id not found.');
//Get index of that course
const index = courses.indexOf(course);
//Remove from db
courses.splice(index,1);
//respond to the request
res.send(course);
});
//VALIDATOR
function validateCourse(course){
const schema = Joi.object({
name: Joi.string().min(3).required()
})
return schema.validate(course);
}
//PORT
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server started on port ${port}...`);
});