๐Ÿ“ฆ SeolJaeHyeok / My-shopping-mall

๐Ÿ“„ order-router.js ยท 101 lines
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
96
97
98
99
100
101import { Router } from "express";
// ํด๋”์—์„œ importํ•˜๋ฉด, ์ž๋™์œผ๋กœ ํด๋”์˜ index.js์—์„œ ๊ฐ€์ ธ์˜ด
import { loginRequired } from "../middlewares";
import { orderService } from "../services";
import { contentTypeChecker } from "../utils/content-type-checker";
const orderRouter = Router();

// ๋‚ด ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ
orderRouter.get("/orderList", loginRequired, async function (req, res, next) {
  try {
    // ํ† ํฐ์—์„œ userId ์ถ”์ถœ
    const userId = req.currentUserId;
    // db์— ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ
    const orderInfo = await orderService.getOrders(userId);
    // front์— ๋ฐ์ดํ„ฐ ์ „๋‹ฌ
    res.status(200).json(orderInfo);
  } catch (error) {
    next(error);
  }
});

// ์ฃผ๋ฌธํ•˜๊ธฐ
orderRouter.post("/complete", loginRequired, async (req, res, next) => {
  try {
    // Content-Type ์ฒดํฌ
    contentTypeChecker(req.body);

    // ํ† ํฐ์—์„œ userId ์ถ”์ถœ
    const userId = req.currentUserId;

    const {
      addressName,
      receiverName,
      receiverPhoneNumber,
      postalCode,
      address1,
      address2,
      request,
      orderList,
      totalPrice,
      shippingFee,
    } = req.body;

    // ๊ฐ ์ฃผ์†Œ ์ •๋ณด๋ฅผ ํ•˜๋‚˜์˜ address ๊ฐ์ฒด์— ์‚ฝ์ž…
    const address = {
      addressName,
      receiverName,
      receiverPhoneNumber,
      postalCode,
      address1,
      address2,
    };
    // ํ•œ ๋ฒˆ ์ฃผ๋ฌธํ•  ๋•Œ ์ƒํ’ˆ์ด ์—ฌ๋Ÿฌ๊ฐœ ์ด๋ฏ€๋กœ, ๊ฐ์ฒด๋กœ ๋ฐ›์•„ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.
    const wholeorderList = Object.values(orderList).map((e) => ({
      productId: e.productId,
      title: e.title,
      quantity: e.quantity,
      price: e.price,
      status: e.status,
    }));

    // db์— ์ฃผ๋ฌธ ์ •๋ณด ์ถ”๊ฐ€
    const newOrder = await orderService.addOrder({
      userId,
      address,
      request,
      orderList: wholeorderList,
      totalPrice,
      shippingFee,
    });

    // front์— ์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ์ฃผ๋ฌธ ์ •๋ณด ์ „๋‹ฌ
    res.status(201).json(newOrder);
  } catch (error) {
    next(error);
  }
});

// ์ฃผ๋ฌธ ์ƒํ’ˆ ์‚ญ์ œ
orderRouter.delete("/delete", loginRequired, async function (req, res, next) {
  try {
    // Content-Type ์ฒดํฌ
    contentTypeChecker(req.body);
    const { orderId, productId } = req.body;
    // ํ† ํฐ์—์„œ userId ์ถ”์ถœ
    const userId = req.currentUserId;
    // db์— ์ฃผ๋ฌธ์˜ ํŠน์ • ์ƒํ’ˆ ์‚ญ์ œ
    const deleteOrderInfo = await orderService.deleteOrderProduct({
      orderId,
      productId,
      userId,
    });
    // front์— ์ฃผ๋ฌธ ์ •๋ณด ์ „๋‹ฌ
    res.status(200).json(deleteOrderInfo);
  } catch (error) {
    next(error);
  }
});

export { orderRouter };