From 759d67e6fbb7e05cd2fc7d532284e91ab428ca6d Mon Sep 17 00:00:00 2001 From: Elliot Hesp Date: Mon, 1 Jun 2020 18:41:04 +0100 Subject: [PATCH] feat(database): add support for ServerValue.increment (#3561) Co-authored-by: Mike Diarmid { + after(() => wipe(TEST_PATH)); + describe('ServerValue.TIMESTAMP', () => { it('returns a valid object', () => { const { TIMESTAMP } = firebase.database.ServerValue; @@ -24,4 +30,36 @@ describe('database.X', () => { TIMESTAMP['.sv'].should.eql('timestamp'); }); }); + + describe('ServerValue.increment', () => { + it('returns a valid object', () => { + const incrementObject = firebase.database.ServerValue.increment(1); + should.equal(Object.keys(incrementObject).length, 1); + incrementObject.should.have.property('.sv'); + incrementObject['.sv'].should.have.property('increment'); + }); + + it('increments on the server', async () => { + const ref = firebase.database().ref(`${TEST_PATH}/increment`); + + await ref.set({ increment: 0 }); + + const res1 = await ref.once('value'); + res1.val().increment.should.equal(0); + + await ref.set({ increment: firebase.database.ServerValue.increment(1) }); + + const res2 = await ref.once('value'); + res2.val().increment.should.equal(1); + }); + + it('increments on the server when no value is present', async () => { + const ref = firebase.database().ref(`${TEST_PATH}/increment-empty`); + + await ref.set({ increment: firebase.database.ServerValue.increment(2) }); + + const res = await ref.once('value'); + res.val().increment.should.equal(2); + }); + }); }); diff --git a/packages/database/lib/DatabaseStatics.js b/packages/database/lib/DatabaseStatics.js index b8cd127c..ca214aff 100644 --- a/packages/database/lib/DatabaseStatics.js +++ b/packages/database/lib/DatabaseStatics.js @@ -20,5 +20,12 @@ export default { TIMESTAMP: { '.sv': 'timestamp', }, + increment(delta: number) { + return { + '.sv': { + increment: delta, + }, + }; + }, }, }; diff --git a/packages/database/lib/index.d.ts b/packages/database/lib/index.d.ts index 8a54d190..8c338dbb 100644 --- a/packages/database/lib/index.d.ts +++ b/packages/database/lib/index.d.ts @@ -73,6 +73,21 @@ export namespace FirebaseDatabaseTypes { * ``` */ TIMESTAMP: object; + + /** + * Returns a placeholder value that can be used to atomically increment the current database value by the provided delta. + * + * #### Example + * + * ```js + * firebase.database().ref('posts/123').update({ + * likes: firebase.database.ServerValue.increment(1), + * }); + * ``` + * + * @param delta The amount to modify the current value atomically. + */ + increment(delta: number): object; } /**