forked from robihamdani/crudnodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
105 lines (82 loc) · 2.1 KB
/
app.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
const express = require("express");
const app = express();
const db = require("./config/db");
app.get("/", (req, res) => res.send("respon nodejs berhasil"));
app.use(express.urlencoded({ extended: true }));
db.authenticate().then(() =>
console.log("berhasil terkoneksi dengan database")
);
const User = require("./models/User");
app.post("/crud", async (req, res) => {
try {
// destructuring object
const { username, email, password } = req.body;
// initialize models database
const newUser = new User({
username,
email,
password
});
// await = menjalankan kode models user
await newUser.save();
// menampilkan newuser ketika di save postman
res.json(newUser);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
});
app.get("/crud", async (req, res) => {
try {
const getAllUser = await User.findAll({});
res.json(getAllUser);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
});
app.get("/crud/:id", async (req, res) => {
try {
const id = req.params.id;
const getUser = await User.findOne({
where: { id: id }
});
res.json(getUser);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
});
app.delete("/crud/:id", async (req, res) => {
try {
const id = req.params.id;
const deleteUser = await User.destroy({
where: { id: id }
});
await deleteUser;
res.json("berhasil di hapus");
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
});
app.put("/crud/:id", async (req, res) => {
try {
const { username, email, password } = req.body;
const id = req.params.id;
const updateUser = await User.update(
{
username,
email,
password
},
{ where: { id: id } }
);
await updateUser;
res.json("berhasil di update");
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
});
app.listen(4500, () => console.log("port bejalan di 4500"));