Skip to content

Instantly share code, notes, and snippets.

@cmawhorter
Last active September 8, 2017 22:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmawhorter/1fe025393efc2545b2c7 to your computer and use it in GitHub Desktop.
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.
// 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