creating a product
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imgUrl = req.body.imgUrl;
const price = req.body.price;
const description = req.body.description;
create
-> for immediately store to db
build -> only for js.. then we need to manually
save it
Product.create({
title: title,
imgUrl: imgUrl,
price: price,
description: description,
})
.then((result) => {
console.log(result);
res.redirect("/");
})
.catch((err) => {
console.log(err);
});
};
GetAll Producsts ->findAll()
exports.getProducts = (req, res, next) => {
Product.findAll()
.then((products) => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
hasProducts: products.length > 0,
active: "products",
});
})
.catch((err) => {
console.log(err);
});
};
new way->async await
-----------------------
exports.getAdminProducts = async (req, res, next) => {
const products = await Product.findAll();
console.log("All Products:", JSON.stringify(products, null, 2));
};
Retrieve Single Product ->findByPk()
exports.getProduct = (req, res, next) => {
const proId = req.params.productId;
Product.findByPk(proId)
.then((product) => {
res.render("shop/product-detail", {
prod: product,
pageTitle: "Product Details",
active: "prod",
hasProduct: true,
});
})
.catch((err) => {
console.log(err);
});
};
Retrieve Single Product ->findAll -where
Product.findAll({ where: { id: proId } })
.then((product) => {
if (!product) {
console.log("NO products
Found...!!!");
res.redirect("/products/ProductIsNotFound");
return;
}
res.render("shop/product-detail", {
prod: product[0],
pageTitle: "Product Details",
active: "prod",
hasProduct: true,
});
})
.catch((err) => {
console.log(err);
});
Updating A Product
exports.postEditProduct = (req, res, next) => {
const uptitle = req.body.title;
const upimgUrl = req.body.imgUrl;
const upprice = req.body.price;
const updescription = req.body.description;
Product.findByPk(prodId)
.then((product) => {
if (!product) {
return res.redirect("/");
}
product.title = uptitle;
product.price = upprice;
product.description = updescription;
product.imgUrl = upimgUrl;
return product.save();
})
.then((result) => {
console.log("Updated
Product");
res.redirect("/admin/products");
})
.catch((err) => {
console.log("ERROR");
});
};
Deleting A product -> .destroy()
exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.findByPk(prodId)
.then((product) => {
if (!product) {
return res.redirect("/");
}
return product.destroy();
})
.then((result) => {
console.log("Updated
Product");
res.redirect("/admin/products");
})
.catch((err) => {
console.log("ERROR");
console.log(err);
});
};

0 Comments