-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (63 loc) · 1.79 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
const Joi = require('joi');
const express = require('express');
const app=express();
app.use(express.json());//middleware
const courses = [
{id:1, name:'math'},
{id:2, name:'science'},
{id:3, name:'history'}];
app.get('/', (req, res) => {
res.send('Wasssssa');
});
app.get('/api/courses', (req, res) => {
res.send(courses);
});
//route params
app.get('/api/doj/:dd/:mm/:yyyy', (req, res) => {
res.send(req.params);
});
//GET requests
app.get('/api/courses/:id', (req, res) => {
let course = courses.find(c => c.id === parseInt(req.params.id));
if(!course) res.status(404);
res.send(course);
});
//POST requests
app.post('/api/courses', (req, res) => {
const schema = { name: Joi.string().min(3).required()};
let result = Joi.valid(req.body, schema);
if(result.error){
res.status(400).send('name is required');
return;
}
let course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});
//Update requests
app.put('/api/courses/:id', (req, res) => {
let course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) res.status(404);
const schema = { name: Joi.string().min(3).required() };
let result = Joi.valid(req.body, schema);
if (result.error) {
res.status(400).send('name is required');
return;
}
course.name = req.body.name;
res.send(course);
});
//delete requests
app.delete('/api/courses/:id', (req, res) =>{
let course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) res.status(404);
const ind = courses.indexOf(course);
courses.splice(ind, 1);
res.send(course);
});
//env var
const port=3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));