product.controller.js 2.11 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import Product from "../schemas/Product.js";
kusang96's avatar
dd    
kusang96 committed
2
3
4
5
6
7
8
9
import multer from 'multer';

const upload = multer({ dest: 'uploads/' })

const imageUpload = upload.fields([
    { name: 'main_image' },
    { name: 'detail_image' }
  ])
Jiwon Yoon's avatar
Jiwon Yoon committed
10
11

const regist = async (req, res) => {
kusang96's avatar
kusang96 committed
12
    console.log("req.body=",req.body)
Jiwon Yoon's avatar
Jiwon Yoon committed
13
    try {
kusang96's avatar
kusang96 committed
14
        const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
kusang96's avatar
dd    
kusang96 committed
15
16
17
18
19
20
21
22
        const main_img = req.files['main_image'][0]
        const detail_img = req.files['detail_image']
        const main_imgUrl = main_img.filename
        const detail_imgUrls = []
        detail_img.forEach(file => {
            detail_imgUrls.push(file.filename)
        })
        const newProduct = await new Product({
kusang96's avatar
kusang96 committed
23
            pro_name, price, stock, main_category, sub_category, description, main_imgUrl, detail_imgUrls, colors, sizes
Jiwon Yoon's avatar
Jiwon Yoon committed
24
25
26
27
        }).save()
        res.json(newProduct)
    } catch (error) {
        console.log(error)
kusang96's avatar
dd    
kusang96 committed
28
        res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.')
Jiwon Yoon's avatar
Jiwon Yoon committed
29
30
31
    }
}

kusang96's avatar
0115    
kusang96 committed
32
33
34
35
36
37
38
39
40
41
42
43
const getToHome = async (res, req) => {
    try {
        const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6)
        const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
        console.log("best=",bestProduct)
        console.log("new=",newProduct)
        res.json(bestProduct, newProduct)
    } catch {
        res.status(500).send('상품을 불러오지 못했습니다.')
    }
}

이재연's avatar
0113    
이재연 committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const getlist=(req,res)=>{
    try {
        res.json(req.productslist)
    } catch (error) {
        res.status(500).send('상품을 불러오지 못했습니다.')
    }
}

const categoryId = async (req, res, next, category) => {
    try {
        const productslist = await Product.find({main_category:category})
        if (!productslist) {
            res.status(404).send('상품을 찾을 수 없습니다.')
        }
        req.productslist = productslist
        next()
    } catch (error) {
        res.status(500).send('상품을 불러오지 못했습니다.')
    }
}
kusang96's avatar
0115    
kusang96 committed
64
export default { imageUpload, regist, categoryId, getlist, getToHome }