我可以将参数传递到与 AWS API Gateway 的 WebSocket 连接中吗?

Mic*_*tin 3 amazon-web-services websocket aws-lambda aws-api-gateway

以下示例项目:https://github.com/aws-samples/simple-websockets-chat-app

onconnect 方法如下所示:

const AWS = require('aws-sdk');

const ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10', region: process.env.AWS_REGION });

exports.handler = async event => {
  const putParams = {
    TableName: process.env.TABLE_NAME,
    Item: {
      connectionId: event.requestContext.connectionId
    }
  };

  try {
    await ddb.put(putParams).promise();
  } catch (err) {
    return { statusCode: 500, body: 'Failed to connect: ' + JSON.stringify(err) };
  }

  return { statusCode: 200, body: 'Connected.' };
};
Run Code Online (Sandbox Code Playgroud)
  1. 我怎样才能看到这个对象还有哪些其他字段event?我找不到文档。

  2. 连接websocket时可以从客户端传入参数吗?就像我如何从这个对象wss://path.to.socket/someparameter访问它?event

我想向数据库添加另一个参数:

const putParams = {
  TableName: process.env.TABLE_NAME,
  Item: {
    connectionId: event.requestContext.connectionId,
    someparameter: event.someparameter               // <-- What's the right way?
  }
};
Run Code Online (Sandbox Code Playgroud)

谢谢!

Lau*_*P22 6

To pass parameters when connecting: wss://path.to.socket?param1=value1&param2=value2.

If using wscat you might need to add quotes:

wscat -c 'wss://path.to.socket?param1=value1&param2=value2'
Run Code Online (Sandbox Code Playgroud)

To access to the parameters from the lambda:

wscat -c 'wss://path.to.socket?param1=value1&param2=value2'
Run Code Online (Sandbox Code Playgroud)