【问题标题】:What extra fields does the AWS Amplify API include when invoking a Lambda function?调用 Lambda 函数时,AWS Amplify API 包括哪些额外字段?
【发布时间】:2020-08-22 13:29:50
【问题描述】:

我有这个 AWS Lambda 函数来在我的 DynamoDB 表中创建一个注释对象:

import * as uuid from "uuid";
import AWS from "aws-sdk";

const dynamoDb = new AWS.DynamoDB.DocumentClient();

export function main(event, context, callback) {
  // Request body is passed in as a JSON encoded string in 'event.body'
  const data = JSON.parse(event.body);

  const params = {
    TableName: process.env.tableName,
    // 'Item' contains the attributes of the item to be created
    // - 'userId': user identities are federated through the
    //             Cognito Identity Pool, we will use the identity id
    //             as the user id of the authenticated user
    // - 'noteId': a unique uuid
    // - 'content': parsed from request body
    // - 'attachment': parsed from request body
    // - 'createdAt': current Unix timestamp
    Item: {
      userId: event.requestContext.identity.cognitoIdentityId,
      noteId: uuid.v1(),
      content: data.content,
      attachment: data.attachment,
      createdAt: Date.now()
    }
  };

  dynamoDb.put(params, (error, data) => {
    // Set response headers to enable CORS (Cross-Origin Resource Sharing)
    const headers = {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": true
    };

    // Return status code 500 on error
    if (error) {
      const response = {
        statusCode: 500,
        headers: headers,
        body: JSON.stringify({ status: false })
      };
      callback(null, response);
      return;
    }

    // Return status code 200 and the newly created item
    const response = {
      statusCode: 200,
      headers: headers,
      body: JSON.stringify(params.Item)
    };
    callback(null, response);
  });
}

它的作用与问题无关。这里需要注意的重要一点是可以通过命令serverless invoke local --function create --path mocks/create-event.json和示例事件create-event.json离线成功执行:

{
  "body": "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}",
  "requestContext": {
    "identity": {
      "cognitoIdentityId": "USER-SUB-1234"
    }
  }
}

但是,当我通过 aws-amplify API 使用 POST 请求调用此 Lambda 函数时,我只在 init 对象中定义了一个 body 字段,即

import { API } from "aws-amplify";
...
function createNote(note) {
  return API.post("scratch-notes", "/scratch-notes", {
    body: note
  });
}

这会导致以下问题......

  • Lambda 函数如何获得所需的requestContext 字段 来自调用它的aws-amplify API POST 方法?
  • 它是否被aws-amplify API 附加到init 对象?

这将是显而易见的答案,但这会引出另一个问题......

  • aws-amplify API 还向 init 对象附加了哪些其他字段?

【问题讨论】:

    标签: javascript aws-lambda serverless-framework aws-amplify aws-serverless


    【解决方案1】:

    event 对象还包含两个额外的结构,afaik:requestContext 对象和 pathParameters 对象。

    requestContext 对象只是包含在 event 对象中的 context 对象,用于测试目的和方便我们。

    pathParameters 对象是从带有特殊标记的路径中提取的字段列表。

      get:
        handler: get.main
        events:
          - http:
              path: scratch-notes/{id}
              method: get
              cors: true
              authorizer: aws_iam
    

    这样的处理程序会接受一个带有 URI scratch-notes/1234 的请求并返回一个 pathParameters 对象,如下所示:

    {
      "pathParameters": {
        "id": "1234"
      }
    }
    

    当然,这两个对象可以结合使用无服务器框架离线调用我们的 API,如下所示:

    {
      "pathParameters": {
        "id": "59747e00-8e61-11ea-8cb8-5d9bcedbe6f4"
      },
      "body": "myBody",
      "requestContext": {
        "identity": {
          "cognitoIdentityId": "USER-SUB-1234"
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 2020-08-22
      • 1970-01-01
      • 2021-03-19
      • 2021-04-25
      • 2021-04-14
      • 2020-11-21
      • 2021-09-23
      • 2020-03-26
      相关资源
      最近更新 更多