diff --git a/packages/database/e2e/DatabaseStatics.e2e.js b/packages/database/e2e/DatabaseStatics.e2e.js index c109de3e..2f1d921e 100644 --- a/packages/database/e2e/DatabaseStatics.e2e.js +++ b/packages/database/e2e/DatabaseStatics.e2e.js @@ -15,7 +15,13 @@ * */ +const { PATH, wipe } = require('./helpers'); + +const TEST_PATH = `${PATH}/statics`; + describe('database.X', () => { + 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; } /**