Last active
September 8, 2017 22:51
-
-
Save cmawhorter/1fe025393efc2545b2c7 to your computer and use it in GitHub Desktop.
Automate DynamoDB doc.update call by generating the required attributes from an object literal.
This file contains 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
// Note: This takes your data keys and drops them directly into the | |
// UpdateExpression. If you have more exotic key names, this will likely | |
// fail because 'this is a valid key name' works in javascript but not the | |
// dynamodb client. | |
var keyName = 'thePartitionKey'; | |
var data = { | |
thePartitionKey: '1231342142321321', | |
message: 'your partial data i.e. the fields you want updated in the target document' | |
}; | |
var updateExpressionStatements = []; | |
var updateExpression; | |
var expressionAttributeNames = {}; | |
var expressionAttributeValues = {}; | |
Object.keys(data).forEach(function(k) { | |
if (k === keyName) return; // skip table keys. they go in a separate param | |
var expressionNameKey = '#' + k; | |
var expressionValueKey = ':' + k; | |
expressionAttributeNames[expressionNameKey] = k; | |
expressionAttributeValues[expressionValueKey] = data[k] | |
updateExpressionStatements.push(expressionNameKey + ' = ' + expressionValueKey); | |
}); | |
updateExpression = 'set ' + updateExpressionStatements.join(', '); | |
var key = {}; | |
key[keyName] = data[keyName]; | |
var params = { | |
UpdateExpression: updateExpression, | |
ExpressionAttributeNames: expressionAttributeNames, | |
ExpressionAttributeValues: expressionAttributeValues, | |
ReturnValues: 'ALL_NEW', | |
Key: key, | |
}; | |
// ugh. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment