无服务器 WebSocket 路由响应

Serverless WebSocket route responses

我正在使用 serverless 创建一个 WebSocket 服务,为此我能够使用 serverless-offline 和已部署的服务在本地成功触发我的 WebSocket 路由。

我现在遇到的问题是响应那些 WS 事件。

我能够使用 AWS.ApiGatewayManagementApi.postToConnection 来响应我的本地 WebSocket 事件,尽管我似乎无法获得我的处理程序的 return 值来实际发送 WebSocket 事件作为响应,因为 these serverless-offline docs and these AWS docs建议。

serverless.yml路线:

  ws-custom:
    handler: handler.wsCustom
    events:
      - websocket:
          route: custom
          routeResponseSelectionExpression: $default

处理人:

module.exports.wsCustom = async (event) => {
  const body = JSON.parse(event.body);
  console.log('WebSocket `custom` event!', event);

  return {
    statusCode: 200,
    body: JSON.stringify({ message: `Hello, ${body.name}!` }),
  };
}

在我的浏览器中调用函数JavaScript:

ws.send(JSON.stringify({ 'action': 'custom', 'name': 'kevbot' }));

结果是我的 serverless-offline 日志(或部署项目中的 CloudWatch)将成功创建一个带有日志的事件,但我的客户端不会收到任何响应事件。 有谁知道我如何使用处理程序的 return 值来做到这一点?

编辑:

问题似乎存在于我的 serverless-offline 设置中。我会尝试让它在本地工作,并会创建一个必要的问题。

使用 WebSocket API 并尝试 return 从您的集成返回客户端的响应时需要注意的重要一点,如 doc 中所述:

For a route that is configured to use AWS_PROXY or LAMBDA_PROXY integration, communication is one-way, and API Gateway will not pass the backend response through to the route response automatically. For example, in the case of LAMBDA_PROXY integration, the body that the Lambda function returns will not be returned to the client. If you want the client to receive integration responses, you must define a route response to make two-way communication possible.

因此,如果您使用代理集成,则无法 return 将响应返回给客户端。您必须使用 AWS.ApiGatewayManagementApi.postToConnection 方法来传送任何数据。

或者,如果您使用的是非代理集成,则可以为集成设置 route response