Created
August 24, 2018 05:18
-
-
Save evanderkoogh/1cf05337e1c230f1d1c61bb46a65a5a8 to your computer and use it in GitHub Desktop.
Add and/or overwrite values in a DynamoDB table with the Document Client
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
const AWS = require('aws-sdk') | |
const docClient = new AWS.DynamoDB.DocumentClient() | |
const mapKeys = (input, transform) => { | |
const output = {} | |
Object.keys(input).forEach((key, index, array) => { | |
output[transform(key, index, array)] = input[key] | |
}) | |
return output | |
} | |
const generateNames = (input) => { | |
const output = {} | |
Object.keys(input).forEach((key, index) => { | |
output[`#${index}`] = key | |
}) | |
return output | |
} | |
const updateExpressions = (update) => { | |
const names = generateNames(update) | |
const values = mapKeys(update, (_, index) => `:${index}`) | |
const expressions = Object.keys(update).map((key, index) => { | |
return `#${index}=:${index}` | |
}) | |
const expression = `SET ${expressions.join(', ')}` | |
return { | |
ExpressionAttributeNames: names, | |
ExpressionAttributeValues: values, | |
UpdateExpression: expression, | |
} | |
} | |
const update = async (table, hashKey, rangeKey, update) => { | |
const updates = updateExpressions(update) | |
const params = { | |
TableName: table, | |
Key: { | |
hashKey, | |
rangeKey, | |
}, | |
...updates, | |
} | |
await docClient.update(params).promise() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let me know if you want me to turn this into an npm package.