Reputation: 207
I have a simple lambda function to write to DynamoDB. I'm trying to access the data that was just written to the database to return it to the client and confirm success.
The code is as follow:
'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}`);
}
};
I can't seem to grab the data written and pass it to the responseBody variable here:
const data = await documentClient.put(params).promise();
responseBody = JSON.stringify(data);
I have a feeling I'm not using the async function correctly but i'm pretty stumped
Upvotes: 1
Views: 301
Reputation: 2545
In the AWS documentation, you can see this option:
ReturnValues: NONE | ALL_OLD | UPDATED_OLD | ALL_NEW | UPDATED_NEW
You can try with it, but I'm not sure it works correctly with PutItem
. The last time when I check it, it works only on UpdateItem
.
The only reliable way to retrieve your inserted object is to GetItem
after the PutItem
, but it's the best solution I think.
When you insert data into the database you already have the data, which will be inserted. So you can return this data to the client.
So, maybe it will be better if you use this way.
Also, I advise you to use the models for the DynamoDB.
Upvotes: 1