Skip to content

Instantly share code, notes, and snippets.

@apaatsio
Last active September 13, 2019 16:13
Show Gist options
  • Save apaatsio/f9f2b408fe02e415629f to your computer and use it in GitHub Desktop.
Save apaatsio/f9f2b408fe02e415629f to your computer and use it in GitHub Desktop.
Single Lambda function for all CRUD operations with DynamoDB in REST API
console.log('Loading function');
var doc = require('dynamodb-doc');
var dynamo = new doc.DynamoDB();
/**
* 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
*/
exports.handler = function(event, context) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var operation = event.operation;
if (event.tableName) {
event.payload.TableName = event.tableName;
}
switch (operation) {
case 'create':
dynamo.putItem(event.payload, context.done);
break;
case 'read':
dynamo.getItem(event.payload, context.done);
break;
case 'update':
dynamo.updateItem(event.payload, context.done);
break;
case 'delete':
dynamo.deleteItem(event.payload, context.done);
break;
case 'list':
dynamo.scan(event.payload, context.done);
break;
case 'echo':
context.succeed(event.payload);
break;
case 'ping':
context.succeed('pong');
break;
default:
context.fail(new Error('Unrecognized operation "' + operation + '"'));
}
};
@karmanya77
Copy link

Still not able to write the data into dynamoDB. "event.payload " is being read as [object Object]. Cannot access the values inside

@apaatsio
Copy link
Author

@karmanya77 This snippet is almost 4 years old and it uses a deprecated npm package (dynamodb-doc). Please, consult other sources for a working and more up-to-date example.

@karmanya77
Copy link

@apaatsio okay.. thanks for the quick response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment