12/09 Amazon API Gateway WebSocket API

Serverless Hello World Advent Calendar 2020째 날이다.
Amazon API Gateway와 AWS Lambda를 사용하여 WebSocket API를 구현합니다.

서비스 작성


웹소켓 API의 템플릿이 없기 때문에 활동 내용 페이지를 보면서 천천히 쓴다.
serverless.yml
service: serverless-helloworld

provider:
  name: aws
  runtime: nodejs12.x
  region: ap-northeast-1

functions:
  default:
    handler: handler.default
    events:
      - websocket: $default
handler.js
'use strict';

const AWS = require('aws-sdk');
AWS.config.update({ region: process.env.AWS_REGION });

module.exports.default = async (event, context) => {
  const client = new AWS.ApiGatewayManagementApi({
    apiVersion: '2018-11-29',
    endpoint: `https://${event.requestContext.domainName}/${event.requestContext.stage}`,
  });

  await client
    .postToConnection({
      ConnectionId: event.requestContext.connectionId,
      Data: `Hello ${event.body || 'World'}!`,
    })
    .promise();

  return {
    statusCode: 200,
  };
};
.gitignore
# package directories
node_modules
jspm_packages

# Serverless directories
.serverless

프로그램 설계


그럼 디버깅 시작하겠습니다.
$ sls deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
........
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service serverless-helloworld.zip file to S3 (483 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.................................
Serverless: Stack update finished...
Service Information
service: serverless-helloworld
stage: dev
region: ap-northeast-1
stack: serverless-helloworld-dev
resources: 12
api keys:
  None
endpoints:
  wss://o92hsw0jf6.execute-api.ap-northeast-1.amazonaws.com/dev
functions:
  default: serverless-helloworld-dev-default
layers:
  None

동작 확인


이번에는 웹소켓, 사용wscat 확인 동작.
$ npm install -g wscat
$ wscat -c wss://o92hsw0jf6.execute-api.ap-northeast-1.amazonaws.com/dev
Connected (press CTRL+C to quit)
> 
< Hello World!
> world
< Hello world!
> ^C
WebSocket API로 작동 중임을 확인합니다.

좋은 웹페이지 즐겨찾기