Skip to content

Commit

Permalink
fix: Add child_changed listener and tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
rakannimer committed Nov 12, 2018
1 parent 90404b6 commit e3a895d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/__tests__/to-map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe("toMap", () => {
config: config.client,
firebase
});
afterAll(async () => {
afterEach(async () => {
const ref = getFirebaseRef({ firebase, path: `${testPath}` });
await ref.set(null);
});
Expand Down Expand Up @@ -101,4 +101,36 @@ Object {
expect(toJS(map)).toMatchInlineSnapshot(`Object {}`);
unsub();
});
test("works with child_changed", async () => {
const ref = getFirebaseRef({ firebase, path: testPath });
const { value: map } = toMap(ref);
await ref.set(listAsObject);
expect(toJS(map)).toMatchInlineSnapshot(`
Object {
"id_0": Object {
"data": 0,
},
"id_1": Object {
"data": 1,
},
}
`);
await firebase
.database()
.ref(testPath + "/id_0")
.update({ NEW: "DATA" });
expect(toJS(map)).toMatchInlineSnapshot(`
Object {
"id_0": Object {
"NEW": "DATA",
"data": 0,
},
"id_1": Object {
"data": 1,
},
}
`);
await ref.set({});
expect(toJS(map)).toMatchInlineSnapshot(`Object {}`);
});
});
18 changes: 18 additions & 0 deletions src/to-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,27 @@ export function toMap<K, V>(
}
map.delete(currentMapKey);
});
const unsubChildChanged = ref.on("child_changed", (v: any) => {
const valueOrNull = !v ? null : v.val();
const keyOrNull = !v ? null : v.key;
const currentMapKey = mapKey(keyOrNull);
const currentMapValue = mapValue(valueOrNull);
if (!map.has(currentMapKey)) {
map.set(currentMapKey, observable.box(currentMapValue));
return;
}

const previousMapValue = map.get(currentMapKey).get();
const shouldUpdateValue = filter(previousMapValue, currentMapValue);
if (!shouldUpdateValue) {
return;
}
map.get(currentMapKey).set(currentMapValue);
});
const unsub = () => {
unsubChildAdded && unsubChildAdded();
unsubChildRemoved && unsubChildRemoved();
unsubChildChanged && unsubChildChanged();
};

return { value: map, unsub };
Expand Down

0 comments on commit e3a895d

Please sign in to comment.