awslabs / dynamodb-data-mapper-js

A schema-based data mapper for Amazon DynamoDB.
https://awslabs.github.io/dynamodb-data-mapper-js/
Apache License 2.0
816 stars 106 forks source link

Add new DataMapper class method, generateUpdateExpression #186

Closed matt-downs closed 2 years ago

matt-downs commented 4 years ago

Description of changes: Add new DataMapper class method, generateUpdateExpression, which gives the ability to extend the update expression generated by existing update method.

Reasoning: I have found myself in a situation where I want to extend the update expression generated by mapper.update, however I don't believe there is an existing way to do this? Specifically I wanted to add some additional REMOVE clauses to the update expression based on some custom logic. Introducing the generateUpdateExpression method allows developers to extend the functionality of the built in mapper.update method without having to generate their own update expression from scratch.

Here is some sample code showing how I am using the new generateUpdateExpression method:

// Newly added method below
const [updateExpression, key, condition] = mapper.generateUpdateExpression(
  Object.assign(new Account(), updates),
  {
    condition: generateUserIdCondition(userId),
    onMissing: "skip",
  }
);

// Ability to extend generated update expression with custom logic before execution
attributesToRemove.forEach((a) => updateExpression.remove(a));

return mapper.executeUpdateExpression(updateExpression, key, Account, {
  condition,
});

Not really too fussed if this doesn't end up in the library, however it helped me in one of my projects so I thought I should PR in case it is a feature that might help others too. For this reason I have not included any unit tests with this PR as I didn't want to invest a heap of time into this change in case it doesn't make it into the lib.

Open to any feedback! :)

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.