forked from zhanggianluca/HTTPBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex.js
72 lines (62 loc) · 1.75 KB
/
ex.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
const express = require("express");
const { read } = require("fs");
const app = express();
app.use(express.json());
app.get('/', (req,res)=> {
res.send('Hello there');
});
const courses = [
{ id: 1, name:'Web Development'},
{ id: 2, name: 'IT'},
{ id: 3, name: 'Cybersecurity'}
];
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) {
req.status(404).send("The course with the given ID was not found");
return
}
res.send(course);
})
//HTTP POST REQUESTS
app.post('/api/courses', (req,res) => {
if (req.body.name.length > 3) {
const course = {
id: courses.length + 1,
name: req.body.name
}
courses.push(course);
res.send(courses);
}
else {
res.status(400).send("Name is required and with a minimum of 4 characters");
}
})
//PUT REQUESTS
app.put("/api/courses/:id", (req, res) => {
const course = courses.find(c=> c.id === parseInt(req.params.id));
if(!course) {
req.status(404).send("The course with the given ID was not found");
return
}
course.name = req.body.name;
course.id = req.body.id;
courses.splice(course.id-1, 1, course)
res.send(course);
})
//DELETE REQUESTS
app.delete("/api/courses/:id", (req, res) => {
const course = courses.find(c=> c.id === parseInt(req.params.id));
if(!course) {
req.status(404).send("The course with the given ID was not found");
return
}
courses.splice(courses.indexOf(course), 1)
res.send(course);
})
app.listen(3000, () => {
console.log("Listening on port 3000 ...");
});