-
Notifications
You must be signed in to change notification settings - Fork 724
/
productController.js
82 lines (59 loc) · 1.72 KB
/
productController.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
const { products } = require('../models')
const db = require('../models')
//create main model
const Product = db.products
const Review = db.reviews
//main work
//1. Create Product
const addProduct = async (req, res)=> {
let info = {
title: req.body.title,
price: req.body.price,
description: req.body.description,
published: req.body.published ? req.body.published : false
}
console.log('Product added', req.body)
const product = await Product.create(info)
res.status(200).send(product);
}
// 2. get all products
const getAllProducts = async (req, res) => {
let products = await Product.findAll({})
res.status(200).send(products)
}
// 3. Get single product
const getOneProduct = async (req, res) => {
let id = req.params.id
let product = await Product.findOne({
where: {id : id}
})
res.status(200).send(product)
}
// 4. Update single product
const updateProduct = async (req, res) => {
let id = req.params.id
const [no, data] = await Product.update(req.body, {where: {id : id}, returning: true} )
let newProduct = await Product.findOne({
where: {id : id}
})
res.status(200).send(newProduct)
}
// 5. delete product by id
const deleteProduct = async (req, res) => {
let id = req.params.id
await Product.destroy({ where: { id : id }})
res.status(200).send('product is deleted')
}
// 6. get published product
const getPublishedProduct = async (req, res) => {
const products = await Product.findAll({ where : { published: true}})
res.status(200).send(products)
}
module.exports = {
addProduct,
getAllProducts,
getOneProduct,
updateProduct,
deleteProduct,
getPublishedProduct
}