-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathadmin.js
More file actions
95 lines (88 loc) · 2.52 KB
/
Copy pathadmin.js
File metadata and controls
95 lines (88 loc) · 2.52 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
const Product = require("../models/product");
exports.getAddProduct = (req, res, next) => {
res.render("admin/edit-product", {
pageTitle: "Add Product",
path: "/admin/add-product",
editing: false,
});
};
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
/**
* @description Magic Association Method
* @summary `.create()` is an in built Method and `Product` is our Model, therefore sequelize creates a
* MAM for us when we use `hasMany` or/and `belongsTo` methods to our models
* */
req.user
.createProduct({
title,
imageUrl,
price,
description,
})
.then(() => res.redirect("/admin/products"))
.catch((err) => console.error(err));
};
exports.getEditProduct = (req, res, next) => {
const editMode = req.query.edit;
if (!editMode) {
return res.redirect("/");
}
const prodId = req.params.productId;
req.user
.getProducts({ where: { id: prodId } })
.then((products) => {
const product = products[0];
if (!product) {
return res.redirect("/");
}
res.render("admin/edit-product", {
pageTitle: "Edit Product",
path: "/admin/edit-product",
editing: editMode,
product: product,
});
})
.catch((err) => console.error(err));
};
exports.postEditProduct = (req, res, next) => {
const prodId = req.body.productId;
const updatedTitle = req.body.title;
const updatedPrice = req.body.price;
const updatedImageUrl = req.body.imageUrl;
const updatedDesc = req.body.description;
Product.findByPk(prodId)
.then((product) => {
product.title = updatedTitle;
product.price = updatedPrice;
product.imageUrl = updatedImageUrl;
product.description = updatedDesc;
return product.save();
})
.then(() => res.redirect("/admin/products"))
.catch((err) => console.log(err));
};
exports.getProducts = (req, res, next) => {
req.user
.getProducts()
.then((products) => {
res.render("admin/products", {
prods: products,
pageTitle: "Admin Products",
path: "/admin/products",
});
})
.catch((err) => console.log(err));
};
exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.findByPk(prodId)
.then((prod) => {
return prod.destroy();
})
.then(() => res.redirect("/admin/products"))
.catch((err) => console.error(err));
};