Created
October 7, 2015 23:52
-
-
Save tzaffi/6ff3a8ff8f4abaac1384 to your computer and use it in GitHub Desktop.
Well Formed AWS Lambda for DynamoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set up AWS client | |
var AWS = require('aws-sdk'); | |
var dynamodb = new AWS.DynamoDB(); | |
// TODO update AWS configuration to set region | |
AWS.config.update({region : 'us-east-1'}); | |
exports.handler = function(event, context) { | |
// Keep tracxk of how many requests are in flight | |
var inflightRequests = 0; | |
event.Records.forEach(function(record) { | |
console.log('DynamoDB Record: %j', record.dynamodb); | |
// Get the new image of the DynamoDB Streams record | |
var newItemImage = record.dynamodb.NewImage; | |
// Set the appropriate parameters for UpdateItem | |
// Refer to the ADD operation in the UpdateItem API for UpdateExpression | |
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html | |
// Adds the specified value to the item, if attribute does not exist, set the attribute | |
var updateItemParams = { | |
TableName: "GameScoresByUser", | |
Key: { | |
Username: newItemImage.Username | |
}, | |
UpdateExpression: 'ADD Score :attrValue', | |
ExpressionAttributeValues: {':attrValue' : newItemImage.Score } | |
} | |
// Make a callback function to execute once UpdateItem request completes | |
// It may be helpful to refer to the updateItem method for the Javascript SDK | |
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#updateItem-property | |
var updateItemCallback = function(err, data) { | |
if (err) { | |
// log errors | |
console.log(err, err.stack); | |
} else { | |
// check if all requests are finished, if so, end the function | |
inflightRequests--; | |
if (inflightRequests === 0) { | |
context.succeed("Successfully processed " + event.Records.length + " records."); | |
} | |
} | |
}; | |
// TODO send UpdateItem request to DynamoDB | |
dynamodb.updateItem(updateItemParams, updateItemCallback); | |
// TODO increase count for number of requests in flight | |
inflightRequests++; | |
}); | |
// If there are no more requests pending, end the function | |
if (inflightRequests === 0) { | |
context.succeed("Successfully processed " + event.Records.length + " records."); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I try this code I get validation errors.
[MultipleValidationErrors: There were 2 validation errors:
Using the DocumentClient seems to fix it:
var dynamodb = new AWS.DynamoDB.DocumentClient();