Skip to content

Instantly share code, notes, and snippets.

@sawilde
Created October 8, 2021 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawilde/1f103c986755c0365c18a1926f8da260 to your computer and use it in GitHub Desktop.
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)
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