-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
122 lines (107 loc) · 2.82 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
113
114
115
116
117
118
119
120
121
122
const express = require('express');
const app = express()
const port = 5000;
app.use(express.json());
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: 'Aspring actress',
},
{
id: 'zap555',
name: 'Dennis',
job: 'Bartender',
}
]
}
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 = findUserByNameAndJob(name, job);
result = {users_list: result};
res.send(result);
} else {
let result = findUserByName(name);
result = {users_list: result};
res.send(result);
}
} else if (job != undefined) {
let result = findUserByJob(job);
result = {users_list: result};
res.send(result);
}
else {
res.send(users);
}
});
const findUserByName = (name) => {
return users['users_list'].filter( (user) => user['name'] === name);
}
const findUserByJob = (job) => {
return users['users_list'].filter( (user) => user['job'] === job);
}
const findUserByNameAndJob = (name, job) => {
return users['users_list'].filter( (user) => user['name'] === name && user['job'] === job);
}
app.get('/users/:id', (req, res) => {
const id = req.params['id']; //or 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);
}
});
function findUserById(id) {
return users['users_list'].find( (user) => user['id'] === id); // or line below
//return users['users_list'].filter( (user) => user['id'] === id);
}
app.post('/users', (req, res) => {
const userToAdd = req.body;
addUser(userToAdd);
res.status(200).end();
});
function addUser(user){
users['users_list'].push(user);
}
app.delete('/users/:id', (req, res) => {
const id = req.params['id'];
let user = findUserById(id);
if (user === undefined || user.length == 0)
res.status(404).send('User not found.');
else {
removeUser(user);
res.status(204).end();
}
});
function removeUser(user){
const index = users['users_list'].indexOf(user);
users['users_list'].splice(index, 1);
}
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});