JAVASCRIPT

node schedule

seo dori 2023. 4. 27. 16:40

DREAM 프로젝트에서 입찰를 기간을 걸어두고 그 기간이 지난다면 유찰로 바꿔주는 작업을 하고 싶었다.

이번 프로젝트를 진행하면서 중요한 포인트중 하나라고 생각했기때문이다. 

 

우선 npm을 다운 받아야한다.

npm install node-schedule

 

 

 

 

node-schedule

A cron-like and not-cron-like job scheduler for Node.. Latest version: 2.1.1, last published: 4 months ago. Start using node-schedule in your project by running `npm i node-schedule`. There are 1561 other projects in the npm registry using node-schedule.

www.npmjs.com

 

 

처음 작성한 코드

입찰기간이 지난 주문의 상태를 유찰상태로 변경시켜주는 코드입니다.

작성하고 직후에는 몰랐었는데 이후에 다른 API를 작성할때 스케줄러가 작동되면서 에러가 생겼었는데

에러를 체크해보니 유찰될 데이터가 없으면 생기는 에러였다....... 

원하는 값이 변경되는 것만 보고 완성했다라고 생각했던 오산이였던 것이다.  

그이후 이 스케줄러가 돌때엔  업데이트될 리스트가 없으면 에러가 날거라는 생각도 안했다.

좀더 깊이 있게 생각하지 못한... 값이 변경되니 신이나버려서

 

const job = schedule.scheduleJob('1 * * * * *', async () => {
  const bidStatus = bidStatusEnum.bid;
  const failStatus = bidStatusEnum.fail;

  let sellingId = await appDataSource.query(
    `SELECT 
    product_id,
    user_id
    FROM sellings
    WHERE due_date < NOW()
    AND bid_status_id = ${bidStatus}`
  );
  sellingId = Array.isArray(sellingId) ? sellingId : [sellingId];
  let sellingProductId = [];
  let sellingUserId = [];

  sellingId.forEach((element) => {
    sellingProductId.push(element.product_id);
    sellingUserId.push(element.user_id);
  });

  let sellProductStr = sellingProductId.join();
  let sellUserStr = sellingUserId.join();

  await appDataSource.query(
    `
    UPDATE
    sellings
    SET bid_status_id = ${failStatus}
    WHERE product_id IN (${sellProductStr})
    AND user_id IN (${sellUserStr})
    `
  );
  const buyingId = await appDataSource.query(
    `SELECT
    product_id,
    user_id
    FROM buyings
    WHERE due_date < NOW()
    AND bid_status_id = ${bidStatus}`
  );
  buyingId = Array.isArray(buyingId) ? buyingId : [buyingId];

  const buyingProductId = [];
  const buyingUserId = [];

  buyingId.forEach((element) => {
    buyingProductId.push(element.product_id);
    buyingUserId.push(element.user_id);
  });

  let buyProductStr = buyingProductId.join();
  let buyUserStr = buyingUserId.join();

  await appDataSource.query(
    `
    UPDATE
    buyings
    SET bid_status_id = ${failStatus}
    WHERE product_id IN (${buyProductStr})
    AND user_id IN (${buyUserStr})
    `
  );
});

 

 

2차 고친 코드 

 

if문을 넣어주어 유찰될 주문이 있다면 나머지를 실행시켜주는 것으로 고쳐주어 유찰될 주문이 없을 때 일어나는 에러를 잡을수 있었다.

 

const job = schedule.scheduleJob('00 06 * * *', async () => {
  const bidStatus = bidStatusEnum.bid;
  const failStatus = bidStatusEnum.fail;

  let sellingId = await appDataSource.query(
    `SELECT 
    product_id,
    user_id
    FROM sellings
    WHERE due_date < NOW()
    AND bid_status_id = ${bidStatus}`
  );

  if (sellingId.length != 0) {
    let sellingProductId = [];
    let sellingUserId = [];

    sellingId.forEach((element) => {
      sellingProductId.push(element.product_id);
      sellingUserId.push(element.user_id);
    });

    let sellProductStr = sellingProductId.join();
    let sellUserStr = sellingUserId.join();

    await appDataSource.query(
      `
    UPDATE
    sellings
    SET bid_status_id = ${failStatus}
    WHERE product_id IN (${sellProductStr})
    AND user_id IN (${sellUserStr})
    `
    );
  }

  let buyingId = await appDataSource.query(
    `SELECT
    product_id,
    user_id
    FROM buyings
    WHERE due_date < NOW()
    AND bid_status_id = ${bidStatus}`
  );

  if (buyingId.length != 0) {
    const buyingProductId = [];
    const buyingUserId = [];

    buyingId.forEach((element) => {
      buyingProductId.push(element.product_id);
      buyingUserId.push(element.user_id);
    });

    let buyProductStr = buyingProductId.join();
    let buyUserStr = buyingUserId.join();

    await appDataSource.query(
      `
    UPDATE
    buyings
    SET bid_status_id = ${failStatus}
    WHERE product_id IN (${buyProductStr})
    AND user_id IN (${buyUserStr})
    `
    );
  }
});

module.exports = { job };