Last active
March 27, 2023 11:45
-
-
Save daverickdunn/4c6a0f61a0b969ec59e589353138bdc3 to your computer and use it in GitHub Desktop.
DynamoDB - Dynamically Build an Update Expression
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 generateUpdateQuery = (fields) => { | |
let exp = { | |
UpdateExpression: 'set', | |
ExpressionAttributeNames: {}, | |
ExpressionAttributeValues: {} | |
} | |
Object.entries(fields).forEach(([key, item]) => { | |
exp.UpdateExpression += ` #${key} = :${key},`; | |
exp.ExpressionAttributeNames[`#${key}`] = key; | |
exp.ExpressionAttributeValues[`:${key}`] = item | |
}) | |
exp.UpdateExpression = exp.UpdateExpression.slice(0, -1); | |
return exp | |
} | |
let data = { | |
'field' : { 'subfield': 123 }, | |
'other': '456' | |
} | |
let expression = generateUpdateQuery(data) | |
let params = { | |
// Key, Table, etc.. | |
...expression | |
} | |
console.log(params) |
Thanks @daverickdunn .. it saves me a lot
This was useful. Thank you very much.
Added a python implementation of the same logic
def generate_update_query(fields):
exp = {
"UpdateExpression": 'set',
"ExpressionAttributeNames": {},
"ExpressionAttributeValues": {}
}
for key, value in fields.items():
exp["UpdateExpression"] += f" #{key} = :{key},"
exp["ExpressionAttributeNames"][f"#{key}"] = key
exp["ExpressionAttributeValues"][f":{key}"] = value
exp["UpdateExpression"] = exp["UpdateExpression"][0:-1]
return exp
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @daverickdunn! Exactly what I was looking for!