Created
October 8, 2021 09:31
-
-
Save sawilde/1f103c986755c0365c18a1926f8da260 to your computer and use it in GitHub Desktop.
safe update of document db by replacing all keys and values by substitutions (avoiding reserved name conflicts)
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
import AWS from 'aws-sdk'; | |
export const TABLE_NAME = 'table_name_here'; | |
export const documentClient = new AWS.DynamoDB.DocumentClient({ | |
region: process.env.TARGET_REGION, | |
}); | |
export const updateRecord = (attributes: any, key: any) => { | |
const map = new Map(Object.entries(attributes)); | |
const keys = Object.keys(attributes); | |
const params = { | |
TableName: TABLE_NAME, | |
Key: key, | |
UpdateExpression: `SET ${keys.map((k, idx) => `#k_${idx} = :v_${idx}`).join(', ')}`, | |
ExpressionAttributeValues: keys.reduce((acc, k, idx) => ({ ...acc, [`:v_${idx}`]: map.get(k) }), {}), | |
ExpressionAttributeNames: keys.reduce((acc, k, idx) => ({ ...acc, [`#k_${idx}`]: k }), {}), | |
ReturnValues: 'UPDATED_NEW', | |
}; | |
return documentClient.update(params).promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment