-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
87 lines (78 loc) · 2.05 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
const express = require('express');
const mysql = require('mysql');
const app = express();
app.use(express.json());
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'crudnode',
});
conn.connect((err) => {
if (err) throw err;
console.log('Koneksi Berhasil');
});
// Menampilkan semua data
app.get('/api/produk', (req, res) => {
conn.query('SELECT * FROM product', (err, result) => {
if (err) {
res.send({ status: 'Gagal', message: err.message });
} else {
res.send({ status: 'Sukses', result });
}
});
});
// Menampilkan bedasarkan ID
app.get('/api/produk/:id', (req, res) => {
conn.query(
`SELECT * FROM product WHERE product_id=${req.params.id}`,
(err, result) => {
if (err) {
res.send({ status: 'Gagal', message: err.name });
} else {
res.send({ status: 'Sukses', result });
}
}
);
});
// Menambahkan data
app.post('/api/produk', (req, res) => {
let data = {
product_name: req.body.product_name,
product_price: req.body.product_price,
};
conn.query(`INSERT INTO product SET ?`, data, (err, result) => {
if (err) {
res.send({ status: 'Gagal', message: err.name });
} else {
res.send({ status: 'Sukses', result });
}
});
});
// Update Data
app.put('/api/produk/:id', (req, res) => {
let sql = `UPDATE product SET product_name="${req.body.product_name}", product_price="${req.body.product_price}" WHERE product_id="${req.params.id}";`;
conn.query(sql, (err, result) => {
if (err) {
res.send({ status: 'Gagal', message: err.name });
} else {
res.send({ status: 'Sukses', result });
}
});
});
// Hapus Data
app.delete('/api/produk/:id', (req, res) => {
conn.query(
`DELETE FROM product WHERE product_id=${req.params.id}`,
(err, result) => {
if (err) {
res.send({ status: 'Gagal', message: err.name });
} else {
res.send({ status: 'Sukses', result });
}
}
);
});
app.listen(6000, () => {
console.log('Server mlaku ngango port 6000');
});