【发布时间】: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-amplifyAPI POST 方法? - 它是否被
aws-amplifyAPI 附加到init对象?
这将是显而易见的答案,但这会引出另一个问题......
-
aws-amplifyAPI 还向init对象附加了哪些其他字段?
【问题讨论】:
标签: javascript aws-lambda serverless-framework aws-amplify aws-serverless