Skip to content

Instantly share code, notes, and snippets.

@evanderkoogh
Created August 24, 2018 05:18
Show Gist options
  • Save evanderkoogh/1cf05337e1c230f1d1c61bb46a65a5a8 to your computer and use it in GitHub Desktop.
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
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()
}
@evanderkoogh
Copy link
Author

Let me know if you want me to turn this into an npm package.

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