-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
99 lines (85 loc) · 2.33 KB
/
server.js
File metadata and controls
99 lines (85 loc) · 2.33 KB
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
const express = require("express");
const mysql = require("mysql2");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(cors());
// MySQL Connection
const db = mysql.createConnection({
host: "host.docker.internal",
user: "root", // apna mysql username
password: "root", // apna mysql password
database: "productdb",
});
db.connect((err) => {
if (err) throw err;
console.log(" MySQL Connected...");
});
// ---------------- API ROUTES ----------------
// Create Product (POST)
app.post("/products", (req, res) => {
const { name, price } = req.body;
db.query(
"INSERT INTO products (name, price) VALUES (?, ?)",
[name, price],
(err, result) => {
if (err) throw err;
res.send({ message: "Product Added", id: result.insertId });
}
);
});
// Get All Products (GET)
app.get("/products", (req, res) => {
db.query("SELECT * FROM products", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
// Update Product (PUT)
app.put("/products/:id", (req, res) => {
const { name, price } = req.body;
db.query(
"UPDATE products SET name=?, price=? WHERE id=?",
[name, price, req.params.id],
(err) => {
if (err) throw err;
res.send({ message: "Product Updated" });
}
);
});
// Delete Product (DELETE)
app.delete("/products/:id", (req, res) => {
db.query("DELETE FROM products WHERE id=?", [req.params.id], (err) => {
if (err) throw err;
res.send({ message: "Product Deleted" });
});
});
// Get single product by ID
app.get("/products/:id", (req, res) => {
const productId = req.params.id;
const sql = "SELECT * FROM products WHERE id = ?";
db.query(sql, [productId], (err, result) => {
if (err) {
return res.status(500).json({ error: "Database error" });
}
if (result.length === 0) {
return res.status(404).json({ message: "Product not found" });
}
res.json(result[0]); // single product return karega
});
});
// Get all products
app.get("/products", (req, res) => {
const sql = "SELECT * FROM products";
db.query(sql, (err, result) => {
if (err) {
return res.status(500).json({ error: "Database error" });
}
res.json(result);
});
});
// Start Server
app.listen(3000, () =>
console.log("🚀 Server running at http://localhost:3000")
);