Skip to content

Commit

Permalink
feat(database): add support for ServerValue.increment (#3561)
Browse files Browse the repository at this point in the history
Co-authored-by: Mike Diarmid <mike.diarmid@gmail.com

[publish]
  • Loading branch information
Ehesp authored Jun 1, 2020
1 parent 6732ceb commit 759d67e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
38 changes: 38 additions & 0 deletions packages/database/e2e/DatabaseStatics.e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
});
});
});
7 changes: 7 additions & 0 deletions packages/database/lib/DatabaseStatics.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,12 @@ export default {
TIMESTAMP: {
'.sv': 'timestamp',
},
increment(delta: number) {
return {
'.sv': {
increment: delta,
},
};
},
},
};
15 changes: 15 additions & 0 deletions packages/database/lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down

0 comments on commit 759d67e

Please sign in to comment.