AWS Lambda에서 dependecy 없이 HTTPS 요청 보내기 - node code snippet
🚅

AWS Lambda에서 dependecy 없이 HTTPS 요청 보내기 - node code snippet

Created
2022/05/26
Tags
AWS
Lambda
AWS Lambda
javascript
node
HTTPS
 
 
2022-05-26 @이영훈
 
AWS Lambda로 HTTPS 요청 보내는 간단한 Lambda를 작성할 일이 종종 있었습니다.
그 때마다 기억이 안나서 이번에 기록으로 남겨둡니다.
 
 
개발하면서 다음의 사항을 고려했습니다.
  1. 빠르게 개발할 수 있어야 합니다.
  1. 그렇기 때문에 custom layer 작성이 필요없는 pre-built library를 사용합니다.
    1. 아직 서울 리전에서는 arm architecture가 도입되지 않아서 (2022.05.26 기준) node, python library를 cross build해야 하는데 이 과정이 번거롭고 힘듭니다
 
 
node를 사용해서 HTTPS 요청을 보내는 AWS Lambda 코드입니다
JavaScript
const https = require('https');

exports.handler = async (event) => {
  console.log("event: ", event);

  const options = {
    hostname: "gist.github.com",  // replace correctly
    port: 443,
    path: '/v1/articles', // replace correctly
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
  };

  // event is json format: {"title": "fancy title", "content: "fancy content..."}
  // replace it correctly
  const dataString = JSON.stringify(event);  

  const promise = new Promise(function (resolve, reject) {
      const req = https.request(options, (res) => {
        res.setEncoding("utf-8");

        let body = '';
        res.on('data', chunk => {
          body += chunk;
        });
        res.on('end', () => resolve(body))
      }).on('error', (e) => {
        reject(Error(e))
      })
      req.write(dataString);
      req.end();
    }
  )

  return promise;
};