From 8fde640f904453259a9895d8dd4ad9f80a548e69 Mon Sep 17 00:00:00 2001 From: james Date: Sat, 24 Dec 2016 08:36:58 -0800 Subject: [PATCH] Document expected parameter use to check an attribute exists --- README.md | 26 ++++++++++++++++++++++ test/integration/integration-test.js | 32 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/README.md b/README.md index b8cf54f..5a79c55 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/test/integration/integration-test.js b/test/integration/integration-test.js index ac7b592..4ef1a79 100644 --- a/test/integration/integration-test.js +++ b/test/integration/integration-test.js @@ -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;