πŸ“Œ Tutorial - Step 1

serverless frameworkλ₯Ό μ΄μš©ν•˜μ—¬ κ°„λ‹¨ν•œ Lambda ν•¨μˆ˜λ₯Ό μƒμ„±ν•˜κ³  λ°°ν¬ν•©λ‹ˆλ‹€.

  1. Serverless νŠœν† λ¦¬μ–Όμ„ ν†΅ν•œ ν”„λ‘œμ νŠΈ 생성
  2. Serverless.yml 레퍼런슀λ₯Ό μ°Έκ³ ν•˜μ—¬ 리전 λ³€κ²½
  3. handler.js νŽΈμ§‘ (μ„œλ²„ κ΅¬ν˜„)
module.exports.hello = async (event) => {
  let inputValue, outputValue
  console.log(event.body)

  if (event.body) {

    let body = JSON.parse(event.body)

    // μΆ”κ°€ λ„μ „κ³Όμ œ: bodyκ°€ { input: 숫자 } κ°€ λ§žλŠ”μ§€ κ²€μ¦ν•˜κ³ , 검증에 μ‹€νŒ¨ν•˜λ©΄ μ‘λ‹΅μ½”λ“œ 400 및 μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό λ°˜ν™˜ν•˜λŠ” μ½”λ“œλ₯Ό λ„£μ–΄λ΄…μ‹œλ‹€.

    inputValue = parseInt(body.input)
    outputValue = inputValue + 1
  }

  const message = `λ©”μ‹œμ§€λ₯Ό λ°›μ•˜μŠ΅λ‹ˆλ‹€. μž…λ ₯κ°’: ${inputValue}, κ²°κ³Ό: ${outputValue}`return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message
      },
      null,
      2
    ),
  };
};
  1. serverless deployλ₯Ό ν†΅ν•œ 배포
  2. cURL을 ν†΅ν•œ ν…ŒμŠ€νŠΈ: μž…λ ₯κ°’μ˜ +1 λ°˜ν™˜

λ‹€μŒκ³Ό 같이 μš”μ²­ν•˜μ—¬ ν•¨μˆ˜ 싀행을 확인할 수 μžˆμŠ΅λ‹ˆλ‹€.

curl -X POST https://API_GATEWAY_ID.execute-api.ap-northeast-2.amazonaws.com \\ --header 'Content-type: application/json' \\ --data-raw '{ "input": 1 }'


βœ” Serverless νŠœν† λ¦¬μ–Όμ„ ν†΅ν•œ ν”„λ‘œμ νŠΈ 생성

npm install --global serverless

serverless

Untitled

serverless.yaml μˆ˜μ •

service: aws-node-http-api-project
frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs18.x
  region: ap-northeast-2

functions:
  api:
    handler: index.handler
    events:
      - httpApi:
          path: /
          method: post

index.js μˆ˜μ •

module.exports.hello = async (event) => {
  let inputValue, outputValue
  console.log(event.body)

  if (event.body) {

    let body;
    try {
      body = JSON.parse(event.body);

      // μΆ”κ°€ λ„μ „κ³Όμ œ: bodyκ°€ { input: 숫자 } κ°€ λ§žλŠ”μ§€ κ²€μ¦ν•˜κ³ , 검증에 μ‹€νŒ¨ν•˜λ©΄ μ‘λ‹΅μ½”λ“œ 400 및 μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό λ°˜ν™˜ν•˜λŠ” μ½”λ“œλ₯Ό λ„£μ–΄λ΄…μ‹œλ‹€.

      // μž…λ ₯확인
      if (typeof body.input !== 'number') {
        return {
          statusCode: 400,
          body: JSON.stringify({
            error: 'μž…λ ₯값이 μ˜¬λ°”λ₯΄μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. 숫자λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.'
          })
        };
      }

      inputValue = parseInt(body.input);
      outputValue = inputValue + 1;
    } catch (error) {
      return {
        statusCode: 400,
        body: JSON.stringify({
          error: 'μ˜¬λ°”λ₯Έ JSON ν˜•μ‹μ΄ μ•„λ‹™λ‹ˆλ‹€.'
        })
      };
    }
  }

  const message = `λ©”μ‹œμ§€λ₯Ό λ°›μ•˜μŠ΅λ‹ˆλ‹€. μž…λ ₯κ°’: ${inputValue}, κ²°κ³Ό: ${outputValue}`

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message
      },
      null,
      2
    ),
  };
};