☁
12/09 Amazon API Gateway WebSocket API
この記事は、Serverless Hello World Advent Calendar 2020の9日目です。
Amazon API GatewayとAWS Lambdaを使ってWebSocket APIを実装します。
サービスの作成
WebSocket APIのテンプレートはないので、Websocketイベントのページを見ながらごりごり書いていきます。
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
動作確認
今回はWebSocketなので、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として動いていることが確認できました。
Discussion