【发布时间】:2021-02-17 04:54:46
【问题描述】:
我有一个简单的 lambda 函数可以写入 DynamoDB。我正在尝试访问刚刚写入数据库的数据以将其返回给客户端并确认成功。
代码如下:
'use strict';
// Config
var AWS = require('aws-sdk');
/* Expected JSON Event
{
"operation": "create",
"tableName": "materials",
"payload": {
"TableName": "materials",
"Item": {
"materialType": "permanent",
"materialId": "1000",
"materialName": "DCP Anchor",
"dimensions": {
"height": 100,
"width": 65,
"diameter": 75
}
}
}
}
* Provide an event that contains the following keys:
*
* - operation: one of the operations in the switch statement below
* - tableName: required for operations that interact with DynamoDB
* - payload: a parameter to pass to the operation being performed
*/
// POST request is in event. We use callback to send the return to client
exports.handler = async (event, context) => {
//console.log('Received event:', JSON.stringify(event, null, 2));
var dynamo = new AWS.DynamoDB.DocumentClient();
// Hardcode Table Name
var tableName = "materials";
event.payload.TableName = tableName;
let responseBody = null;
let statusCode = null;
switch (event.operation) {
case 'create':
try {
const data = await dynamo.put(event.payload).promise();
responseBody = JSON.stringify(data)
statusCode = 201;
} catch (err){
responseBody = `Unable to put: ${err}`;
statusCode = 403;
}
const response = {
statusCode,
headers: {
"Content-Type" : "application/json"
},
body: responseBody
};
return response;
default:
return (`Unknown operation: ${event.operation}`);
}
};
我似乎无法在这里抓取写入的数据并将其传递给 responseBody 变量:
const data = await documentClient.put(params).promise();
responseBody = JSON.stringify(data);
我感觉我没有正确使用异步功能,但我很困惑
【问题讨论】:
-
嗨尼尔帕克。请检查答案并将问题标记为已回答。谢谢!
标签: javascript amazon-web-services aws-lambda amazon-dynamodb