-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
115 lines (108 loc) · 2.75 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
const express = require("express");
const app = express();
const port = 3000;
const db = require("./connection");
app.use(express.json());
app.get("/", (req, res) => {
res.send(
"Hello Ini Adalah Api Node Js yaitu Basic Restfull Api Menggunakan Express JS"
);
});
app.get("/products", (req, res) => {
const sqlQuery = "SELECT * FROM products";
db.query(sqlQuery, (err, result) => {
if (result.length > 0) {
res.json({
status: 200,
payload: result,
message: "success",
});
} else {
res.json({
status: 400,
payload: result,
message: "bad",
});
}
});
});
app.get("/products/:id", (req, res) => {
const idProducts = req.params.id;
const sqlQuery = `SELECT * FROM products WHERE id = ${id}`;
db.query(sqlQuery, (err, result) => {
if (result.length > 0) {
res.json({
status: 200,
payload: result,
message: "success ambil data products",
});
} else {
res.json({
status: 400,
payload: result,
message: "gagal ambil data products",
});
}
});
});
app.post("/products/:id", (req, res) => {
const body = req.body;
const sqlQuery = `INSERT INTO products set nama = "${body.nama}",stok = ${body.stok},kategori = "${body.kategori}",deskripsi = "${body.deskripsi}"`;
db.query(sqlQuery, (err, result) => {
if (result.length > 0) {
res.json({
status: 200,
payload: result,
message: "success post products",
});
} else {
res.json({
status: 400,
payload: results,
message: "gagal post products",
});
}
});
});
app.put("/products/:id", (req, res) => {
const id = req.params.id;
const body = req.body;
const sqlQuery = `UPDATE products set nama = "${body.nama}",stok=${body.stok}, kategori = "${body.kategori}", deskripsi = "${body.deskripsi}" where id = ${id}`;
db.query(sqlQuery, (err, result) => {
if (result.length > 0) {
res.json({
status: 200,
payload: result,
message: "success update products",
});
} else {
res.json({
status: 400,
payload: result,
message: "gagal update products",
});
}
});
});
app.delete("/products/:id", (req, res) => {
const id = req.params.id;
const sqlQuery = `DELETE FROM products where id = ${id}`;
db.query(sqlQuery, (err, result) => {
if (result.affectedRows > 0) {
res.json({
status: 200,
payload: result,
message: "success delete products",
});
} else {
res.json({
status: 400,
payload: result,
message: "gagal delete products",
});
}
});
});
app.listen(port, () => {
console.log(`service - api jalan diport : ${port}`);
});