TIL

TIL - 쇼핑몰 프로젝트 (Plain Old) 13일 차. 옵션 별 상품 주문 구현.

김뚜루 2023. 2. 15. 12:33

쇼핑몰 프로젝트 13일 차.

옵션아이템 별로 수량을 설정해서 주문할 수 있는 기능을 구현했다.

현재 구현하고자 하는 쇼핑몰은 상품의 사이즈와 색상 별로 주문할 수 있게 할 예정이라 동일한 T-Shirt 상품이여도 옵션아이템 별로 수량을 다르게 설정해서 주문할 수 있어야 했다.

구현 자체는 지난번 레벨테스트 때 OrderSpecificationStore을 구현했던 경험이 있어 그렇게 어렵지 않았지만 옵션아이템 별로 관리하려 하니 또 다른 느낌이 들었다.

그런데 말이지.

옵션아이템 수량…그걸 관리하는 Store…?

오 이거 홀맨님이 FECONF에서 소개하셨던 microStore가 딱 이 모양이지 않았었나?!

문뜩 생각이나 참고해서 OrderItem을 관리하는 Store를 구현하게 되었다.

아래는 아직 수정을 해야하지만 대강 완성된 Store 코드

class OrderSpecificationStore extends Store {
  constructor() {
    super();

    this.orderSpecification = new OrderSpecification();
  }

  addOrderItem(orderItem) {
    this.orderSpecification = this.orderSpecification.addOrderItem(orderItem);

    this.publish();
  }

  updateOrderItem({ index, change }) {
    this.orderSpecification = this.orderSpecification.updateOrderItem(
      { index, change },
    );

    this.publish();
  }

//...
}

class OrderSpecification {
  constructor(orderItems = []) {
    this.orderItems = orderItems;
  }

  addOrderItem(orderItem) {
    return new OrderSpecification([...this.orderItems, orderItem]);
  }

  updateOrderItem({ index, change }) {
    const orderItem = this.orderItems.at(index);

    return new OrderSpecification([
      ...this.orderItems.slice(0, index),
      new OrderItem({
        ...orderItem,
        quantity: orderItem.quantity + change,
      }),
      ...this.orderItems.slice(index + 1)]);
  }

  totalQuantity() {
    if (this.orderItems.length === 0) {
      return 0;
    }

    return this.orderItems.reduce((acc, current) => (acc + current.quantity), 0);
  }

  totalCost() {
    if (this.orderItems.length === 0) {
      return 0;
    }

    return this.orderItems.reduce((acc, current) => (acc + current.totalPrice), 0);
  } 

//....
}

class OrderItem {
  constructor({
    id, price, name, thumbnailUrl, shippingFee, freeShippingAmount, quantity,
  }) {
    this.id = id;
    this.price = price;
    this.name = name;
    this.thumbnailUrl = thumbnailUrl;
    this.shippingFee = shippingFee;
    this.freeShippingAmount = freeShippingAmount;
    this.quantity = quantity || 1;
    this.totalPrice = this.price * this.quantity;
  }
}

 

그런데 말입니다.

최근 코딩도장에 독감 유행이 돌고 있는데 나도 독감인지는 모르겠으나 감기증상이 꽤 나타나고 있다.

월요일에 코딩도장 나갈 수 있으려나… 컨디션이 안좋으니 코딩도 잘 안되고.

감기 따위 언능 떨쳐내야지 화이팅!