diff --git a/src/database/database.spec.ts b/src/database/database.spec.ts index 7e27e45..c16f9e6 100644 --- a/src/database/database.spec.ts +++ b/src/database/database.spec.ts @@ -533,6 +533,12 @@ export const Ref = { ref: {key: 'key-1'}, push: undefined, resolve: undefined, + handlers: { + // dumb handler to avoid checks + 'child_added': () => {} + }, + on(event, callback) { this.handlers[event] = callback; }, + off(event) { this.handlers[event] = () => {}; }, toString: () => 'https://angularfire2-offline.firebaseio.com/key-1', database: { ref: () => { @@ -545,9 +551,11 @@ export const Ref = { }; @Injectable() -export class MockFirebaseListObservable extends Subject { +export class MockFirebaseListObservable extends Subject> { history = []; $ref = Ref.$ref; + oldValue: Array = []; + constructor() { super(); } @@ -555,6 +563,25 @@ export class MockFirebaseListObservable extends Subject { this.history.push('remove'); return new Promise(resolve => resolve()); } + + next(value: Array) { + let i = 0, j = 0; + + while (i < this.oldValue.length && j < value.length) { + if ((value[i]).key < (this.oldValue[j]).key) { + this.child_added(value[i], j === 0 ? null : (this.oldValue[j - 1]).key); + } else if ((value[i]).key > (this.oldValue[j]).key) { + j++; // TODO call child_removed + } else if ((value[i]).val() !== (this.oldValue[j]).val()) { + i++; j++; // TODO call child_changed + } + } + + this.oldValue = value; + super.next(value); + } + child_added = (value, previousChild) => + this.$ref.handlers['child_added'](value, previousChild); } @Injectable() diff --git a/src/database/database.ts b/src/database/database.ts index 2b45195..3fc1626 100644 --- a/src/database/database.ts +++ b/src/database/database.ts @@ -307,11 +307,25 @@ export class AngularFireOfflineDatabase { } else { this.listCache[key].sub.uniqueNext( cacheValue ); } - this.setList(key, value); + }); + + ref.$ref.on('child_added', (childSnapshot: any, prevChildName: any) => { + let parentKey = childSnapshot.ref.parent.key; + this.localForage.setItem(`read/object${parentKey}/${childSnapshot.key}`, childSnapshot.val()); + this.localForage.getItem(`read/list${parentKey}`) + .then(keys => keys.reduce( + (arr, _key) => { + _key === prevChildName ? arr.push(_key, childSnapshot.key) : arr.push(_key); + return arr; + }), []) + .then(keys => this.localForage.setItem(`read/list${parentKey}`, keys)); }); this.listCache[key].sub.subscribe({ - complete: () => subscription.unsubscribe() + complete: () => { + subscription.unsubscribe(); + ref.$ref.off('child_added'); + } }); // Local