-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCRUDUser_v2.js
More file actions
225 lines (211 loc) · 7.08 KB
/
CRUDUser_v2.js
File metadata and controls
225 lines (211 loc) · 7.08 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
const express = require('express');
const app = express();
const port = 3000;
const fs = require('fs');
const bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// CRUD users: Create, Read, Update, Delete
// Write file include array of user.
const users = [
{
id: 1,
email: 'user1@gamil.com',
password: 'abc123',
gender: 'male'
},
{
id: 2,
email: 'user2@gamil.com',
password: 'abc123',
gender: 'male'
}
];
function readFileSync(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) {
return reject(err);
}
const fileContent = JSON.parse(data);
return resolve(fileContent);
});
});
}
function writeFileSync(filePath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, data, (err) => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
checkExistUser = (id, users) => {
for (const item of users) {
if (item.id === id) {
return false;
}
}
return true;
}
getIndexUser = (users, id) => {
let index = -1;
users.map((item, key) => {
if (item.id === id) {
index = key;
}
});
return index;
}
// Get one user api
app.get('/users/getById/:userId', async (req, res) => {
try {
const users = await readFileSync('users.txt');
const userId = req.params.userId;
const index = getIndexUser(users, parseInt(userId));
if (index !== -1) {
return res.status(200).json({ user: users[index] });
}
// for (const item of users) {
// if (item.id === parseInt(userId)) {
// return res.status(200).json({ user: item });
// }
// }
return res.status(400).json({ message: 'User is not found' });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
// Create one user api
app.post('/users/post', async (req, res) => {
try {
const body = req.body;
if (!body.id) {
return res.status(400).json({ message: 'ID is the require field' });
}
if (!body.email) {
return res.status(400).json({ message: 'Email is the require field' });
}
if (!body.password) {
return res.status(400).json({ message: 'Password is the require field' });
}
const users = await readFileSync('users.txt');
body.id = parseInt(body.id);
if (!checkExistUser(body.id, users)) {
return res.status(400).json({ message: 'User is exist!' });
}
users.push({
id: body.id,
email: body.email,
password: body.password,
gender: body.gender,
createdAt: new Date()
});
await writeFileSync('users.txt', JSON.stringify(users, null, 2));
return res.status(200).json({ message: 'Successful', user: body });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
app.get('/users/write', async (req, res) => {
try {
await writeFileSync('users.txt', JSON.stringify(users, null, 2));
return res.status(200).json({ message: 'Successful' });
} catch (e) {
return res.status(400).json({ message: 'Cannot write user file', error: e.message });
}
});
app.get('/users/read', async (req, res) => {
try {
const data = await readFileSync('users.txt');
return res.status(200).json({ message: 'Successful', data });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
// Delete one user api
app.delete('/users/delete/:userId', async (req, res) => {
try {
const users = await readFileSync('users.txt');
const userId = req.params.userId;
const index = getIndexUser(users, parseInt(userId));
if (index !== -1) {
users.splice(index, 1);
await writeFileSync('users.txt', JSON.stringify(users, null, 2));
return res.status(200).json({ message: 'Delete success!' });
}
return res.status(400).json({ message: 'User is not found' });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
// Update one user api
app.put('/users/update/:userId', async (req, res) => {
try {
const body = req.body;
const users = await readFileSync('users.txt');
const userId = req.params.userId;
const index = getIndexUser(users, parseInt(userId));
if (userId !== body.id) {
return res.status(400).json({ message: 'Not update ID' });
}
if (!body.id) {
return res.status(400).json({ message: 'ID is the require field' });
}
if (!body.email) {
return res.status(400).json({ message: 'Email is the require field' });
}
if (!body.password) {
return res.status(400).json({ message: 'Password is the require field' });
}
if (index !== -1) {
users[index].email = body.email;
users[index].password = body.password;
users[index].gender = body.gender;
await writeFileSync('users.txt', JSON.stringify(users, null, 2));
return res.status(200).json({ message: 'Success!' });
}
return res.status(400).json({ message: 'User is not found' });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
app.get('/users/search/:email', async (req, res) => {
try {
const users = await readFileSync('users.txt');
const email = req.params.email;
let results = [];
for (const item of users) {
if (item.email === email) {
results.push(item);
}
}
if (results.length > 0) {
return res.status(200).json({ users: results });
}
return res.status(400).json({ message: 'User is not found' });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
app.get('/users/search/regex/:name', async (req, res) => {
try {
const users = await readFileSync('users.txt');
const email = req.params.name;
let results = [];
for (const item of users) {
if (item.email.indexOf(email) !== -1) {
results.push(item);
}
}
if (results.length > 0) {
return res.status(200).json({ users: results });
}
return res.status(400).json({ message: 'User is not found!' });
} catch (e) {
return res.status(400).json({ message: 'Cannot read user file', error: e.message });
}
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));