-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrud.js
102 lines (93 loc) · 2.37 KB
/
crud.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
const express = require("express");
// const res = require("express/lib/response");
app = express();
app.use(express.json());
const accounts = [
{
id: 1,
username: "paulhal",
role: "admin",
},
{
id: 2,
username: "johndoe",
role: "guest",
},
{
id: 3,
username: "sarahjane",
role: "guest",
},
];
//read data from an object
app.get("/accounts", (req, res) => {
res.json(accounts);
});
//get indiividual data from an object
app.get("/accounts/:id", (req, res) => {
const found = accounts.some(
(account) => account.id === parseInt(req.params.id)
);
if (found) {
res.json(
accounts.filter((account) => account.id === parseInt(req.params.id))
);
} else {
res.status(400).json({ msg: `no account with the id of ${req.params.id}` });
}
});
// adding new data
app.post("/accounts", (req, res) => {
const newAccount = {
id: req.body.id,
username: req.body.username,
role: req.body.role,
};
if (!newAccount.id || !newAccount.username || !newAccount.role) {
res.status(400).json({ msg: "Please include id, username and role" });
} else {
accounts.push(newAccount);
res.json(accounts);
}
});
//updating data
app.put("/accounts/:id", (req, res) => {
const found = accounts.some(
(account) => account.id === parseInt(req.params.id)
);
if (found) {
const updatedAccount = req.body;
accounts.forEach((account) => {
if (account.id === parseInt(req.params.id)) {
account.username = updatedAccount.username
? updatedAccount.username
: accounts.name;
account.role = updatedAccount.role
? updatedAccount.role
: accounts.name;
res.json({ msg: `account updated`, accounts });
}
});
} else {
res.status(400).json({ msg: `no account with the id of ${req.params.id}` });
}
});
//deleting data
app.delete("/accounts/:id", (req, res) => {
//.some is used in array to test all the data
const found = accounts.some(
(account) => account.id === parseInt(req.params.id)
);
if (found) {
res.json({
msg: "member deleted",
account: accounts.filter(
(account) => account.id !== parseInt(req.params.id)
),
});
} else {
res.status(400).json({ msg: `no account with the id of ${req.params.id}` });
}
});
PORT = 5050;
app.listen(PORT, () => console.log(`server running at : ${PORT}`));