-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
88 lines (68 loc) · 2.07 KB
/
server.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 { response } = require('express');
const express = require('express');
const emoji = require('node-emoji');
const MOCK_USERS = require('./users.json');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (request, response) => {
response.send('200 OK');
});
let users = [];
app.get('/users', (request, response) => {
response.json(users);
});
app.get('/init', (req, res) => {
MOCK_USERS.forEach(u => {
createNewUser(u);
})
res.json(users);
})
app.get('/users/:id', (request, response) => {
const userId = Number(request.params.id);
const user = users.find((user) => user.id === userId);
if (!user) {
response.status(404).send(`User with id=${userId} not found.`)
} else {
response.json(user);
}
});
app.post('/users', (request, response) => {
const reqDto = request.body;
if (isRequestHasRequiredProps(reqDto)) {
createNewUser(reqDto);
response.json(users);
} else {
response.status(400).send("Request DTO must have ['name', 'surname', 'patronymic', 'dateBirth', 'gender'] fields");
}
})
app.post('/reset', (request, response) => {
if (request.body && request.body.sure) {
users = [];
response.json(users);
return;
}
response.status(400).send('Need confirm');
})
app.listen(PORT, () => {
console.log(`Express server currently running on port ${PORT}`);
console.log(emoji.random());
});
function isRequestHasRequiredProps(dto) {
const requiredFields = ['name', 'surname', 'patronymic', 'dateBirth', 'gender'];
const keys = Object.keys(dto);
return requiredFields.every(f => keys.indexOf(f) > -1);
}
function createNewUser(dto) {
if (!dto) {
return {};
}
const newUser = {
id: users.length + 1,
fullName: `${dto.surname} ${dto.name} ${dto.patronymic}`,
dateBirth: dto.dateBirth,
gender: dto.gender,
avatar: emoji.random().emoji
}
users.push(newUser);
}