使用无服务器的自定义api网关websocket端点

时间:2019-05-12 06:59:11

标签: websocket aws-api-gateway serverless-framework

我试图通过无服务器自定义api网关websocket端点,因为我需要针对在websocket之前部署的cloudfront对其进行初始化。 初始化代码如下:

ApiGatewayWebsocketApi: 
      Type: AWS::ApiGatewayV2::Api
      Properties:
        Name: ${self:provider.stage}-${self:provider.variant}-WebsocketApi
        ProtocolType: WEBSOCKET
        RouteSelectionExpression: "$request.body.action"
        Description: "WebSocket API for ${self:provider.variant}"

然后将其导出为输出:

ApiGatewayWebsocketApiId:
          Value: 
            Ref: ApiGatewayWebsocketApi
          Export:
            Name: ${self:custom.configFile.appCode}-${self:provider.stage}-${self:provider.variant}-ApiGatewayWebsocketApiId

然后ApiGatewayWebsocketApiId将代表端点字符串,例如b6hnpuyzq6

我可以在websocket serverless.yml中得到它:

 WebSocketApiId:
    Fn::ImportValue: ${self:custom.configFile.appCode}-${self:provider.stage}-${self:provider.variant}-ApiGatewayWebsocketApiId

但这是问题所在: 如何将其导入到我的函数(例如connectionHandler)中,以便此websocket可以使用上面导入的端点:

  connectionHandler:
    name: ${self:provider.stage}-${self:provider.variant}-${self:custom.configFile.appCode}-ws-connection
    handler: WebsocketTestHandler
    events:
      - websocket:
          route: $connect
      - websocket:
          route: $disconnect

1 个答案:

答案 0 :(得分:0)

也许您可以尝试通过处理程序中可用的WebSocketApiId参数值槽WEB_SOCKET_API_ID环境变量,就像这样:

  connectionHandler:
    name: ${self:provider.stage}-${self:provider.variant}-${self:custom.configFile.appCode}-ws-connection
    handler: WebsocketTestHandler
    environment:
      WEB_SOCKET_API_ID:
        Ref: WebSocketApiId
    events:
      - websocket:
          route: $connect
      - websocket:
          route: $disconnect