when doing updates on a document, we usually want to selectively update some fields, or remove other ones. this becomes more complex if you have multiple keys in a document or indexes as the requirements for changing the values of those fields are more strict. the following is a method which gives you the required attributes for doing a dynamic update:
private makeAttributeExpressions = (
fields: Record<string, any>,
documentKeys: string[],
) => {
const exp = {
UpdateExpression: '',
ExpressionAttributeNames: {},
ExpressionAttributeValues: {},
};
let setExpression = '';
let removeExpression = '';
Object.entries(fields).forEach(([key, item]) => {
exp.ExpressionAttributeNames[`#${key}`] = key;
if (documentKeys.includes(key)) {
return;
}
if (item) {
setExpression += ` #${key} = :${key},`;
exp.ExpressionAttributeValues[`:${key}`] = item || null;
} else {
removeExpression += ` #${key},`;
}
});
setExpression = 'SET ' + setExpression.slice(0, -1);
removeExpression =
removeExpression.length > 0
? 'REMOVE ' + removeExpression.slice(0, -1)
: '';
exp.UpdateExpression = setExpression + ' ' + removeExpression;
return exp;
};