-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
114 lines (99 loc) · 2.08 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const express = require('express');
const app = express();
const port = 5000;
const users = {
users_list :
[
{
id: 'xyz789',
name: 'Charlie',
job: 'Janitor',
},
{
id: 'abc123',
name: 'Mac',
job: 'Bouncer',
},
{
id: 'ppp222',
name: 'Mac',
job: 'Professor',
},
{
id: 'yat999',
name: 'Dee',
job: 'Aspiring actress',
},
{
id: 'zap555',
name: 'Dennis',
job: 'Bartender',
},
]
}
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/users', (req, res) => {
const name = req.query.name;
const job = req.query.job;
if (name != undefined){
if (job != undefined){
let result = findUserByNameJob(name, job);
result = {users_list: result};
res.send(result);
}
else {
let result = findUserByName(name);
result = {users_list: result};
res.send(result);
}
}
else {
res.send(users);
}
});
app.get('/users/:id', (req, res) => {
const id = req.params['id'];
let result = findUserById(id);
if (result === undefined || result.length == 0)
res.status(404).send('Resource not found. ');
else {
result = {users_list: result};
res.send(result);
}
});
app.post('/users', (req, res) => {
const userToAdd = req.body;
addUser(userToAdd);
res.status(200).end();
});
app.delete('/users/:id', (req, res) => {
const id = req.params['id'];
let result = findUserById(id);
if (result === undefined || result.length == 0)
res.status(404).send('Resource not found. ');
else {
deleteUser(result);
res.status(200);
}
});
function deleteUser(user) {
users['users_list'].pop(user);
}
function addUser(user) {
users['users_list'].push(user);
}
function findUserById(id) {
return users['users_list'].find( (user) => user['id'] === id);
}
function findUserByNameJob(name, job) {
return users['users_list'].find( ((user) => user['name'] === name) && ((user) => user['job'] === job))
}
const findUserByName = (name) => {
return users['users_list'].filter( (user) => user['name'] === name);
}
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});