Bug fix: Products No image

This commit is contained in:
Mann Patel
2025-03-24 23:04:12 -06:00
parent fc125cc76a
commit e7a6e1dd8b
5 changed files with 139 additions and 106 deletions

View File

@@ -7,7 +7,7 @@ exports.addToFavorite = async (req, res) => {
// Use parameterized query to prevent SQL injection
const [result] = await db.execute(
"INSERT INTO Favorites (UserID, ProductID) VALUES (?, ?)",
[userID, productsID]
[userID, productsID],
);
res.json({
@@ -20,18 +20,22 @@ exports.addToFavorite = async (req, res) => {
}
};
//Get all products
// Get all products along with their image URLs
exports.getAllProducts = async (req, res) => {
try {
const [data, fields] = await db.execute("SELECT * FROM Product");
const [data, fields] = await db.execute(`
SELECT p.*, i.URL
FROM Product p
LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
`);
res.json({
success: true,
message: "Product added to favorites successfully",
message: "Products fetched successfully",
data,
});
} catch (error) {
console.error("Error finding user:", error);
console.error("Error finding products:", error);
return res.status(500).json({
found: false,
error: "Database error occurred",
@@ -39,6 +43,48 @@ exports.getAllProducts = async (req, res) => {
}
};
// Get a single product by ID along with image URLs
exports.getProductById = async (req, res) => {
const { id } = req.params;
console.log(id);
try {
const [data] = await db.execute(
`
SELECT p.*, i.URL AS image_url
FROM Product p
LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
WHERE p.ProductID = ?
`,
[id],
);
if (data.length === 0) {
return res.status(404).json({
success: false,
message: "Product not found",
});
}
// Assuming that `data` contains product information and the image URLs
const product = {
...data[0], // First product found in the query
images: data.map((image) => image.image_url), // Collect all image URLs into an array
};
res.json({
success: true,
message: "Product fetched successfully",
data: product,
});
} catch (error) {
console.error("Error fetching product:", error);
return res.status(500).json({
success: false,
error: "Database error occurred",
});
}
};
// db_con.query(
// "SELECT ProductID FROM product WHERE ProductID = ?",
// [productID],

View File

@@ -1,5 +1,9 @@
const express = require("express");
const { addToFavorite, getAllProducts } = require("../controllers/product");
const {
addToFavorite,
getAllProducts,
getProductById,
} = require("../controllers/product");
const router = express.Router();
@@ -7,4 +11,6 @@ router.post("/add_fav_product", addToFavorite);
router.get("/get_product", getAllProducts);
router.post("/get_productID", getProductById);
module.exports = router;