-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
97 lines (65 loc) · 2.18 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
95
96
97
require('dotenv').config();
const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());
const users = [
{id: 1, fname: 'Sepehr', lname: 'Soltanieh'},
{id: 2, fname: 'Shideh', lname: 'Bendokht'},
{id: 3, fname: 'Sahand', lname: 'Soltanieh'}
];
app.get('/', (req, res) => res.send('Hello, world!'));
app.get('/api/users', (req, res) => res.send(users));
app.get('/api/users/:id', (req, res) => {
// 1 id => yes => find & validate
// 2 reqBody => no
// 3 res => calculate => send
const user = users.find(user => user.id=== parseInt(req.params.id));
if (!user) return res.status(404).send('User not found!');
res.send(user);
});
app.post('/api/users', (req, res) => {
// 1 id => no
// 2 reqBody => yes => validate
// 3 res => calculate => send
const { error } = validateNewUser(req.body);
if (error) return res.status(400).send(error.details[0].message);
const user = {
id: users.length + 1,
fname: req.body.fname,
lname: req.body.lname
};
users.push(user);
res.send(user);
});
app.put('/api/users/:id', (req, res) => {
// 1 id => yes => find & validate
// 2 reqBody => yes => validate
// 3 res => calculate => send
const user = users.find(user => user.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found!');
const { error } = validateNewUser(req.body);
if (error) return res.status(400).send(error.details[0].message);
user.fname = req.body.fname;
user.lname = req.body.lname;
res.send(user);
});
app.delete('/api/users/:id', (req, res) => {
// 1 id => yes => find & validate
// 2 reqBody => no
// 3 res => calculate => send
const user = users.find(user => user.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found!');
const index = users.indexOf(user);
users.splice(index, 1);
res.send(user);
});
function validateNewUser(reqBody) {
const schema = {
fname: Joi.string().min(3),
lname: Joi.string().max(5).required()
};
return Joi.validate(reqBody, schema);
}
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));