diff --git a/src/index.js b/src/index.js index b287bf9..87104bd 100644 --- a/src/index.js +++ b/src/index.js @@ -395,13 +395,13 @@ class SuperRepo { * @param {Number} _interval - the interval, in milliseconds * @return {Void} */ - _initSyncInterval(_interval) { + _initSyncInterval(_interval, _cb) { // Do not initiate intervals which are quicker then a second, // otherwise, this might be a big network (performance) overhead. const interval = _interval < 1000 ? 1000: _interval; return setInterval( - () => this._requestFreshData(), interval + () => this._requestFreshData().then(_cb), interval ); } @@ -412,7 +412,7 @@ class SuperRepo { * * @return {Void} */ - initSyncer() { + initSyncer(_cb = () => {}) { const { outOfDateAfter } = this.config; return new Promise(_resolve => { @@ -427,13 +427,14 @@ class SuperRepo { const diff = new Date().valueOf() - _res.lastFetched; let remainingTime = outOfDateAfter - diff; - this.syncInterval = this._initSyncInterval(remainingTime); + this.syncInterval = + this._initSyncInterval(remainingTime, _cb); setTimeout( () => { this.destroySyncer(); this.syncInterval = - this._initSyncInterval(outOfDateAfter); + this._initSyncInterval(outOfDateAfter, _cb); }, remainingTime < 1000 ? 1000 : remainingTime); _resolve(); @@ -441,8 +442,9 @@ class SuperRepo { this._requestFreshData() .then(_response => { this.syncInterval = - this._initSyncInterval(outOfDateAfter); + this._initSyncInterval(outOfDateAfter, _cb); + _cb(); _resolve(); }); } diff --git a/test/data-sync.js b/test/data-sync.js index 9b0e035..20cdeb3 100644 --- a/test/data-sync.js +++ b/test/data-sync.js @@ -264,4 +264,48 @@ describe('Data Sync', () => { expect(networkRequestsCount).to.equal(13); }).then(done, done); }); + + it('Should fire a success callback as soon as the background data sync process gets fresh data. Use case: there is no data.', done => { + const callback = sinon.spy(); + + expect(callback.callCount).to.equal(0); + + repository.initSyncer(callback).then( () => { + expect(callback.callCount).to.equal(1); + + clock.tick(TIMEFRAME - 1); + expect(callback.callCount).to.equal(1); + + clock.tick(1); + expect(callback.callCount).to.equal(2); + + clock.tick(TIMEFRAME); + expect(callback.callCount).to.equal(3); + }).then(done, done); + }); + + it('Should fire a success callback as soon as the background data sync process gets fresh data. Use case: there is data.', done => { + const callback = sinon.spy(); + + repository.getData().then(() => { + expect(callback.callCount).to.equal(0); + + repository.initSyncer(callback).then( () => { + expect(callback.callCount).to.equal(0); + + clock.tick(TIMEFRAME - 1); + expect(callback.callCount).to.equal(0); + + clock.tick(1); + expect(callback.callCount).to.equal(1); + + clock.tick(TIMEFRAME); + expect(callback.callCount).to.equal(2); + + clock.tick(10 * TIMEFRAME); + expect(callback.callCount).to.equal(12); + }).then(done, done); + + }); + }); });