Project 3: Day 3

이준석·2023년 2월 22일
0

Project 3

목록 보기
5/5

Step 4 : 데이터베이스의 재고를 증가시키는 Lambda 함수 생성


  1. 데이터베이스의 재고를 증가시키는 Lambda 함수(stock-increase-lambda)를 배포

  2. stock_lambda에서 레거시 시스템(Factory API)에 제품 생산 요청

Factory-API Document

  • Method

    • POST
  • Path

    • /api/manufactures
  • Request Body Schema : application/json

{
  MessageGroupId : string(메시지 그룹 아이디) //"stock-arrival-group",
  MessageAttributeProductId : string(추가 생산이 필요한 제품 아이디),
  MessageAttributeProductCnt : string(추가 생산 요청 수량),
  MessageAttributeFactoryId : string(추가 생산을 요청할 공장 아이디),
  MessageAttributeRequester : string(추가 생산 요청 담당자)
}

위의 Factory API 문서를 활용하여, 코드를 작성해야 합니다.

  • stock_lambda 프로젝트에 npm install axios 명령으로 axios 라이브러리를 설치해야 합니다.
    axios는 node.js에서 HTTP 명령을 보내는 라이브러리입니다. (fetch와 유사)

  • 코드 맨 윗줄에 const axios = require('axios').default를 추가합니다.

  • 다음 코드를 활용하여 Factory API에 제품 생산을 요청하세요.

const payload = {
  // TODO:
  // 어떤 형식으로 넣어야 할까요? Factory API 문서를 참고하세요.
  // 필요하다면 record.body를 활용하세요.
}

 axios.post('http://project3-factory-api.coz-devops.click/api/manufactures', payload)
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

  • Sales API에서 메시지를 SNS에 발행할 때 때 Factory API에 필요한 정보를 같이 넘겨야 합니다.
    Factory API에 맞게 params를 수정해야 할 것입니다.

stock-lambda

const axios = require('axios').default

//function delay(time) {
//  return new Promise(resolve => setTimeout(resolve, time));
//}

module.exports.hello = async (event) => {
// await delay(15000)
  const result = JSON.parse(event.Records[0].body)
  console.log(result)
    const payload = {
      MessageGroupId : result.MessageId,
      MessageAttributeProductId : result.MessageAttributes.MessageAttributeProductId.Value,
      MessageAttributeProductCnt : 10,
      MessageAttributeFactoryId : result.MessageAttributes.MessageAttributeFactoryId.Value,
      MessageAttributeRequester : "이준석",
      CallbackUrl : "https://7xjxnjdbt6.execute-api.ap-northeast-2.amazonaws.com/product/donut"
    }
  console.log(payload)
    
     axios.post('http://project3-factory-api.coz-devops.click/api/manufactures', payload)
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  }

stock-increase-lambda

app.post("/product/donut", connectDb, async (req, res, next) => {
  const [ result ] = await req.conn.query(
    getProduct('CP-502101')
  )
  if (result.length > 0) {
    const product = result[0]
    const incremental = req.body.MessageAttributeProductCnt || 0

    await req.conn.query(increaseStock(product.product_id, incremental))
    return res.status(200).json({ message: `입고 완료! 남은 재고: ${product.stock + incremental}`});
  } else {
    return res.status(400).json({ message: "상품 없음" });
  }
});

완성 다이어그램

수정 다이어그램

0개의 댓글