-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (45 loc) · 1.26 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
const express = require('express');
const { uid } = require('uid');
const port = 3000;
const app = express();
app.use(express.json());
let users = [];
app.get('/api/users', (req, res) => {
res.json({ users: users });
});
app.post('/api/users', (req, res) => {
const user = { ...req.body, id: uid() };
users.push(user);
res.status(201).json(user);
});
app.get('/api/user/:id', (req, res) => {
const id = req.params.id;
const index = users.findIndex((user) => user.id === id);
if (index === -1) {
res.status(404).send({ status: 'not found' });
return;
}
res.status(200).json(users[index]);
});
app.put('/api/user/:id', (req, res) => {
const id = req.params.id;
const index = users.findIndex((user) => user.id === id);
if (index === -1) {
res.status(404).send({ status: 'not found' });
return;
}
users[index] = { ...req.body };
res.status(200).json(users[index]);
});
app.delete('/api/user/:id', (req, res) => {
const id = req.params.id;
const index = users.findIndex((user) => user.id === id);
if (index === -1) {
res.status(404).send({ status: 'not found' });
return;
}
const deletedUser = users[index];
users = users.filter((user) => user.id !== id);
res.status(200).json(deletedUser);
});
module.exports = app;