본문 바로가기

⭐ AWS/AWS API Gateway

AWS API Gateway Websocket with Lambda Authorizer

# 해당 내용에 대한 AWS 관련 URL은 아래와 같다.

https://aws.amazon.com/ko/blogs/compute/announcing-websocket-apis-in-amazon-api-gateway/

 

Announcing WebSocket APIs in Amazon API Gateway | Amazon Web Services

This post is courtesy of Diego Magalhaes, AWS Senior Solutions Architect – World Wide Public Sector-Canada & JT Thompson, AWS Principal Software Development Engineer – Amazon API Gateway Starting today, you can build bidirectional communication applic

aws.amazon.com

1. 람다 함수 생성하기

- 웹 소켓의 엔드포인드 연결을 위한 람다 함수 생성

- 추후에 람다에서 웹소켓 API를 사용하기 위한 권한 설정 필요

함수 생성하기

- 람다 서비스로 이동하여 함수를 생성

이름은 임의의 이름을 입력

노드 버전도 20.x정도로 하고 생성한다.

권한은 기본 권한 가지고 생성되도록 설정

2. 람다 함수에 소스코드 넣기

- 아래 코드를 복사하여 붙여넣기, endpoint에는 후에 생성하는 API Gateway Websocket의 정보를 넣어주면 된다.

const AWS = require('aws-sdk')

const api = new AWS.ApiGatewayManagementApi({
  endpoint: '{api gw ws endpoint address wss:// 빼고 넣으면 된다.}'
})

const options = ['Yes', 'No', 'Maybe', 'Probably', 'Probably Not']

exports.handler = async (event) => {
    console.log(event)

    const route = event.requestContext.routeKey
    const connectionId = event.requestContext.connectionId

    switch (route) {
        case '$connect':
            console.log('Connection occurred')
            break
        case '$disconnect':
            console.log('Disconnection occurred')
            break
        case 'message':
            console.log('Received message:', event.requestContext.body)
            await replyToMessage(options[Math.floor(Math.random() * options.length)], connectionId)
            break
        default:
            console.log('Received unknown route:', route)
    }

    return {
      statusCode: 200
    }
}

async function replyToMessage(response, connectionId) {
    const data = { message: response }
    const params = {
      ConnectionId: connectionId,
      Data: Buffer.from(JSON.stringify(data))
    }

    return api.postToConnection(params).promise()
}

- 함수를 작성하고 Deploy 즉 배포를 해줘야 반영이 된다. 참고!

3. API Gateway Websocket을 생성

- 이름은 임의의 이름을 지정

- 라우팅 표현식은 request.body.action 입력

- 경로추가 → $connect, $disconnect, message 경로 추가 버튼을 클릭 후 추가

4. 통합 연결 구성

- 통합 연결 구성하기, 통합 연결은 람다 함수를 연결한다.

- 스테이지 추가 화면에서 production을 입력 후 다음으로 넘어간다.

보통 dev, stage, production으로 진행

5. 테스트

API Gateway Websocket을 생성하면 최종적으로 경로가 제공된다.

WebSocket URL, @connections URL

WebSocket URL의 정보를 lambda 코드에 endpoint 주소에 넣어준다.

- 람다 엔드포인트 주소를 변경해주고 배포를 한다.

- 주의 할점은 node 버전이 올라가면서 .mjs로 생성이 되는 부분이 있다. 그러면서 아래와 같이 에러가 발생할수 있는데,

에러 내용 : require is not defined in ES module scope, you can use import instead

이럴땐 mjs를 js로 변경해 주고 다시 배포 후 테스트를 진행해보자.

그리고 권한 문제로 안될수도 있으니, 권한 부분도 체크를 해봐야 한다. 권한은 보통 람다 권한 문제가 가장 많으므로 람다의 권한을 체크해보자. 람다 권한체크 정보는 아래와 같다. 역할에 들어가서 권한을 설정해 주면 된다. (리소스 기반 정책 설명도 나중에 한번 봐야한다.)

- 테스트 화면

 

- 끝 -