Node.js

서버 가동하기, API 수정필터링 추가하기

selonjulie 2022. 8. 11. 10:03

스펙: typescript, express, sequelize

 

1. 경로

 

경로를 볼때는 보통

app 에서 최상위 경로를 보고,

    this.application.use("/user", userRoute.router);
    this.application.use("/job", jobRoute.router);
    this.application.use("/notice", noticeRoute.router);
    this.application.use("/admin", adminRoute.router);
    this.application.use("/cheer", cheerRoute.router);
    this.application.use("/item", itemRoute.router);

그 아래 router부분에 들어가서 그 뒤 주소를 확인한다

    // 상품 리스트
    this.router.get("/list", checkTokenAuth, itemController.getItems);
    // 상품 조회
    this.router.get("/", checkTokenAuth, itemController.getItem);
    // 상품 추가
    this.router.post("/", checkTokenAuth, itemController.addItem);
    // 상품 수정
    this.router.put("/", checkTokenAuth, itemController.editItem);
    // 상품 상태 수정
    this.router.put("/status", checkTokenAuth, itemController.editItemStatus);
    // 상품 삭제
    this.router.delete("/", checkTokenAuth, itemController.deleteItem);

    // 삭제 상품 리스트
    this.router.get("/delete/list", checkTokenAuth, itemController.getDeleteItems);
    // 삭제 상품 복구
    this.router.put("/delete/recover", checkTokenAuth, itemController.recoverDeleteItem);

결국 내가 postman에서 작성해야할 주소는 두개를 합친 아래와 같이 된다

 

2. 직접 페이지를 열어보기 위해서는

.env 파일 생성하여 아래와 같이 백서버를 정의해준다. config파일에 어떻게 서버가 연결되어 있는지 확인하기

SERVER_URL = http://localhost:3000

백서버를 가동하기

프론트 npm 혹은 yarn을 설치하고, build -> start

주소창에 열때는 프론트 포트를 확인하여 연다

localhost:3000

 

3.코드

 

controller

/**
   * 삭제 상품 리스트
   * @param req
   * @param res
   * @param next
   */
  public async getDeleteItems(req: Request, res: Response, next: NextFunction) {
    try {
      // 현재 페이지
      const page = Number(misc.param(req.query, "page", 0));
      // 가져올 수
      const count = Number(misc.param(req.query, "count", 30));

      //부모 카테고리 식별아이디
      const pCategoryUid = misc.param(req.query, "pCategoryUid", null);
      let categorySeq = null;
      let pCategorySeq = null;

      //부모 카테고리 조회
      if (pCategoryUid !== null) {
        const category = await categoryService.getCategory({ uid: pCategoryUid }, true);
        if (category === null) {
          throw result.badRequest("조회할 수 없습니다.");
        }
        pCategorySeq = category.categorySeq;

        //하위 카테고리를 여러개 담고 IN으로 받음
        let categorySeqs = null;
        categorySeqs = await categoryService.getCategorySeqsByPcategory({ pCategorySeq });
        categorySeq = categorySeqs.categoryArr;
      }

      //하위 카테고리 식별아이디
      const categoryUid = misc.param(req.query, "categoryUid", null);

      //하위 카테고리 조회
      if (categoryUid !== null) {
        const category = await categoryService.getCategory({ uid: categoryUid }, true);
        if (category === null) {
          throw result.badRequest("조회할 수 없는 카테고리입니다.");
        }
        categorySeq = category.categorySeq;
      }

      const { items, total } = await itemService.getDeleteItems({
        page,
        count,
        categorySeq,
      });
      next(result.ok({ items, total }));
    } catch (e) {
      next(e);
    }
  }

service

  /**
   * 삭제 상품 리스트
   * @param data
   * @returns
   */
  public async getDeleteItems(data: { page: number; count: number; categorySeq?: number | null }) {
    try {
      let where: any = {
        type: {
          [Op.not]: 1,
        },
        status: 2,
      };

      //하위 카테고리 리스트
      if (data.categorySeq !== null) {
        where = {
          ...where,
          categorySeq: data.categorySeq,
        };
      }

      let items = await Item.scope("list").findAll({
        where: {
          ...where,
        },
        offset: data.page * data.count,
        limit: data.count,
        order: [["itemSeq", "DESC"]],
      });
      items = JSON.parse(JSON.stringify(items));

      const total = await Item.scope("list").findAndCountAll({
        where: {
          ...where,
        },
      });

      return { items, total: total.rows.length };
    } catch (e) {
      throw e;
    }
  }

Express 

express | request

req.query

This property is an object containing a property for each query string parameter in the route. When query parser is set to disabled, it is an empty object {}, otherwise it is the result of the configured query parser.

  /**
   * 카테고리 조회
   * @param data
   * @returns
   */
  public async getCategory(data: { uid?: string }, detail: boolean = false) {
    try {
      let category = await Category.scope(detail ? "all" : "detail").findOne({
        where: {
          ...data,
        },
      });
      if (category !== null) {
        category = category.toJSON() as Category;
      }
      return category;
    } catch (e) {
      throw e;
    }
  }

  /**
   * 상위 카테고리로 하위 카테고리 categorySeq를 배열로 조회
   * @param data
   * @returns
   */
  public async getCategorySeqsByPcategory(data: { pCategorySeq?: number | null }) {
    try {
      let categorys = await Category.scope("all").findAll({
        where: {
          ...data,
        },
        attributes: ["categorySeq"],
      });
      const categoryArr = categorys.map((el) => el.categorySeq);
      return { categoryArr };
    } catch (e) {
      throw e;
    }
  }

'Node.js' 카테고리의 다른 글

사용자 URL주소와 백엔드 요청 API주소 구분하기  (0) 2022.08.11
중복 검사 로직  (0) 2022.08.10
API 수정관련 코드 리뷰, 회사 서버 운영  (0) 2022.08.10
프론트 서버 돌리는 방법  (0) 2022.08.08
미들웨어  (0) 2022.06.19