키오스크 개발 + 오류 대처법

김민준·2023년 8월 4일
0
  1. nodemon(서버 자동재시작)
  2. git 줄바꿈 에러
  3. 오류가 떴을 때 대처절차
  4. Sequelize 복수형
  5. 키오스크 개발

공부하며 느낀 점
참조한 사이트

1. nodemon(서버 자동재시작)

npm install -g nodemon
설치 후 서버를 실행할때 nodemon만 붙이면 된다.
node app

node nodemon app

2. git 줄바꿈 에러

warning: in the working copy of '<파일명>'LF will be replaced by CRLF the next time Git touches it

원인 window에서는 CRLF(\r\n) 유닉스(MAC, Linux) 에서는 LF(\n) 를 이용하여 줄바꿈을 하는데, 이것이 통일되지 않아서 발생하는 오류라고 한다.

자신이 윈도우더라도 협업할때는 유닉스에 맞추는게 일반적이기 때문에 LF로 통일하는 것이 좋다고한다.

해결법 1.

  1. 프로젝트 최상위 폴더에 .gitattributes 파일을 생성한다.
  2. 내용에 * text=auto eol=lf 를 적어서 LF로 통일한다.

해결법 2.

git config --global core.autocrlf true 명령어로 글로벌로 LF 줄바꿈으로 통일한다.
현재 프로젝트에면 적용하고 싶으면 --global을 떼면된다.

설정을 제거하고 싶다면
git config --global --unset core.autocrlf 를 하면된다고 한다.

해결법 1을 추천한다. 왜냐하면 컴퓨터를 바꾸거나, 다른 팀원이 파일을 받았을 때 설정이 적용되어야하며, 글로벌로 해놓고 잊고 살다가 다른데서 문제가 생길수도 있다.

3. 오류가 떴을 때 대처절차

  1. 절대로 이것이 오류의 원인이라고 단정하고 시작하지 않는다.

  2. 오류가 떴다 > 내가 무엇을 오류라고 생각했는가?
    모든 오류가 오류 메시지가 뜨지 않는다. 코드는 잘 작동했지만 내가 원한 결과물이 나오지 않는다면 그것도 오류이다.

  3. 오류 메시지도 마찬가지다. 모든 오류가 메시지를 반환하거나 메시지에 나타나지는 않는다.

  4. 내가 짠 코드뿐 아니라, 환경설정, 디펜던시(OS, 배포환경, 라이브러리 등등) 등의 문제도 고려한다.

4. Sequelize 복수형

Sequelize는 모델 이름을 기반으로 테이블을 만들때 복수형으로 만든다고한다. 별도로 테이블명을 지정할 수 는 있으나, 언제 어떻게 오류가 터질지 모르니 처음부터 테이블명은 복수형으로 생각하자.

5. 키오스크 개발

이어짐

 itemOrderUpdate_Service = async (orderID, status) => {
    try {
      if (
        status !== "ORDERED" &&
        status !== "PENDING" &&
        status !== "COMPLETED" &&
        status !== "CANCELED"
      ) {
        return {
          status: 400,
          message:
            "적절한 발주 상태를 입력해주세요. (ORDERED, PENDING, COMPLETED, CANCELED)",
        };
      }

      const statusNow = await this.ItemOrderRepositories.getStatusById(
        orderID,
        status
      );

      if (statusNow.state === status) {
        return {
          status: 400,
          message: "발주를 같은 상태로 바꿀 수 없습니다.",
        };
      } else if (statusNow.state === "COMPLETED") {
        console.log("컴플상태");
        const itemAmount = await this.ItemOrderRepositories.getItemById(
          statusNow.item_id
        );
        console.log(itemAmount.amount, statusNow.amount);
        if (itemAmount.amount < statusNow.amount) {
          return {
            status: 400,
            message: "재고가 부족하여 반송할 수 없습니다.",
          };
        }
      }
      const statusUpdate = await this.ItemOrderRepositories.patchStatusById(
        orderID,
        status
      );

      if (statusUpdate === 1) {
        const statusNow = await this.ItemOrderRepositories.getStatusById(
          orderID,
          status
        );
      }
      var amountNow = statusNow.amount;
      var idNow = statusNow.item_id;
      var stateNow = statusNow.state;

      var pluMin;

      if (stateNow === "COMPLETED") {
        pluMin = -1;
      } else if (stateNow !== "COMPLETED") {
        pluMin = 1;
      }
      await this.ItemOrderRepositories.patchItemAmount(
        idNow,
        pluMin,
        amountNow
      );
      return { status: 200, message: "발주 수정이 완료되었습니다." };
    } catch (err) {
      return { status: 400, message: err.message };
    }
  };
//  발주 상태 업데이트
  // 발주 상태 확인
  getStatusById = async (orderID) => {
    const statusNow = await Order_item.findOne({
      where: { id: orderID },
      attributes: except(),
    });
    return statusNow;
  };
  // 발주 상태 갱신
  patchStatusById = async (orderID, state) => {
    const statusUpdate = await Order_item.update(
      {
        state,
      },
      {
        where: { id: orderID },
        attributes: except(),
      }
    );
    return statusUpdate;
  };

  patchItemAmount = async (item_id, positiv, amountNow) => {
    const posAmount = positiv * amountNow;
    const amountUpdate = await Item.increment(
      { amount: posAmount },
      {
        where: { id: item_id },
        attributes: except(),
      }
    );
    return amountUpdate;
  };

발주 상태 업데이트에 따른 실제 품목의 증감은 구현했다.
이제 트랜잭션만 잘먹이면된다. 쉽지않음...

트랜잭션 성공

//  3repository/itemOrderRepository.js

const Item = require("../0DB/models/item");
const Order_item = require("../0DB/models/order_item");
const { except } = require("../0DB/models/except");
// const { sequelize } = require("../0DB/models");
// models가 아니라 models에서 배열로 내보낸 Item의 sequelize를 가져와야한다...
const models = require("../0DB/models");
const sequelize = models[0].sequelize;
const { QueryTypes } = require("sequelize");

어젯밤에 트랜잭션이 안됐던 이유는 간단했다...
sequelize객체를 제대로 가져오지 못했기 때문이다.
models.js 에서

module.exports = [
  Item,
  Item_order_customer,
  Option,
  Order_customer,
  Order_item,
];

라는 배열의 형태로 Item을 내보내고 있었기 때문에, Item의 sequelize를 가져와야 했던 것이다.
진짜로 아 다르고 어 다르다.

//  발주 상태 업데이트
  // 발주 상태 확인
  getStatusById = async (orderID) => {
    const statusNow = await sequelize.transaction(async (t) => {
      return Order_item.findOne({
        where: { id: orderID },
        attributes: except(),
        transaction: t,
      });
    });

    return statusNow;
  };
  // 발주 상태 갱신
  patchStatusById = async (orderID, state) => {
    const statusUpdate = await sequelize.transaction(async (t) => {
      return Order_item.update(
        {
          state,
        },
        {
          where: { id: orderID },
          attributes: except(),
          transaction: t,
        }
      );
    });

    return statusUpdate;
  };

  patchItemAmount = async (item_id, positiv, amountNow) => {
    const posAmount = positiv * amountNow;

    const amountUpdate = await sequelize.transaction(async (t) => {
      return Item.increment(
        { amount: posAmount },
        {
          where: { id: item_id },
          attributes: except(),
          transaction: t,
        }
      );
    });

    return amountUpdate;
  };

아무튼 위와같은 형태로 트랜잭션을 구현해내었다.

공부하며 느낀 점

  1. git을 통해서 협업을 하면 서로 다른 환경에서 개발하는 경우가 있다. 이럴때 환경 설정을 바꾼다면, 되도록이면 파일로 바꾸도록하자. 그래야 다른 환경에서 협업하는 사람도 알 수 있다.
  2. 사용하는 라이브러리나 프레임 워크의 특징을 파악해서 애초에 오류가 안뜨게 설정하자

참조한 사이트

Sequelize.increment
트랜잭션 적용하기

[Git 경고 메세지] LF will be replaced by CRLF in 해결 방안
Git 에러 CRLF will be replaced by LF (혹은 반대) 핸들링하는 방법

profile
node 개발자

0개의 댓글

관련 채용 정보