Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document expected parameter use to check an attribute exists #53

Merged
merged 1 commit into from
Jan 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,32 @@ Account.update({email: 'foo@example.com', age: null}, function (err, acc) {
});
```

To ensure that an item exists before updating, use the `expected` parameter to check the existence of the hash key. The hash key must exist for every DynamoDB item. This will return an error if the item does not exist.
```js
Account.update(
{ email: 'foo@example.com', name: 'FooBar Testers' },
{ expected: { email: { Exists: true } } },
(err, acc) => {
console.log(acc.get('name')); // FooBar Testers
}
);

Account.update(
{ email: 'baz@example.com', name: 'Bar Tester' },
{ expected: { email: { Exists: true } } },
(err, acc) => {
console.log(err); // Condition Expression failed: no Account with that hash key
}
);
```

This is essentially short-hand for:
```js
var params = {};
params.ConditionExpression = 'attribute_exists(#hashKey)';
params.ExpressionAttributeNames = { '#hashKey' : 'email' };
```

You can also pass what action to perform when updating a given attribute
Use $add to increment or decrement numbers and add values to sets

Expand Down
32 changes: 32 additions & 0 deletions test/integration/integration-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,38 @@ describe('Dynogels Integration Tests', function () {
});
});

it('should use expected to check that the item exists', (done) => {
User.update(
{
id: '123456789',
email: 'updated_already@exists.com'
},
{
expected: { id: { Exists: true } }
},
(err, acc) => {
expect(err).to.not.exist;
expect(acc).to.exist;
expect(acc.attrs.email).to.eql('updated_already@exists.com');
done();
}
);
});

it('should fail when expected exists check fails', (done) => {
User.update(
{
id: 'does not exist'
},
{ expected: { id: { Exists: true } } },
(err, acc) => {
expect(err).to.exist;
expect(acc).to.not.exist;
done();
}
);
});

it('should remove name attribute from user record when set to empty string', done => {
User.update({ id: '9999', name: '' }, (err, acc) => {
expect(err).to.not.exist;
Expand Down