Skip to content

Commit 57df078

Browse files
committed
added missing DataSnapshot methods - child, exists, getPriority, hasChild, hasChildren, numChildren
1 parent 12b1f4f commit 57df078

File tree

1 file changed

+42
-9
lines changed

1 file changed

+42
-9
lines changed

lib/modules/database/snapshot.js

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,80 @@
22
* @flow
33
*/
44
import Reference from './reference.js';
5+
import { isObject, deepGet } from './../../utils';
56

67
export default class Snapshot {
78
static key: String;
89
static value: Object;
910
static exists: boolean;
1011
static hasChildren: boolean;
11-
static childrenCount: Number;
1212
static childKeys: String[];
1313

1414
ref: Object;
1515
key: string;
1616
value: any;
1717
exists: boolean;
1818
priority: any;
19-
hasChildren: boolean;
20-
childrenCount: number;
2119
childKeys: Array<string>;
2220

2321
constructor(ref: Reference, snapshot: Object) {
2422
this.ref = ref;
2523
this.key = snapshot.key;
2624
this.value = snapshot.value;
2725
this.exists = snapshot.exists || true;
28-
this.priority = snapshot.priority;
29-
this.hasChildren = snapshot.hasChildren || false;
30-
this.childrenCount = snapshot.childrenCount || 0;
26+
this.priority = snapshot.priority === undefined ? null : snapshot.priority;
3127
this.childKeys = snapshot.childKeys || [];
3228
}
29+
/*
30+
* DEFAULT API METHODS
31+
*/
3332

3433
val() {
3534
return this.value;
3635
}
3736

37+
child(path: string) {
38+
const value = deepGet(this.value, path);
39+
const childRef = this.ref.child(path);
40+
return new Snapshot(childRef, {
41+
value,
42+
key: childRef.key,
43+
exists: value !== null,
44+
childKeys: isObject(value) ? Object.keys(value) : [],
45+
});
46+
}
47+
48+
exists() {
49+
return this.value !== null;
50+
}
51+
3852
forEach(fn: (key: any) => any) {
39-
(this.childKeys || [])
40-
.forEach(key => fn(this.value[key]));
53+
(this.childKeys || []).forEach((key, i) => fn(this.value[key], i));
54+
}
55+
56+
getPriority() {
57+
return this.priority;
58+
}
59+
60+
hasChild(key: string) {
61+
return this.childKeys.includes(key);
62+
}
63+
64+
hasChildren() {
65+
return this.numChildren() > 0;
66+
}
67+
68+
numChildren() {
69+
if (!isObject(this.value)) return 0;
70+
return Object.keys(this.value).length;
4171
}
4272

73+
/*
74+
* EXTRA API METHODS
75+
*/
4376
map(fn: (key: string) => mixed) {
4477
const arr = [];
45-
this.forEach(item => arr.push(fn(item)));
78+
this.forEach((item, i) => arr.push(fn(item, i)));
4679
return arr;
4780
}
4881

0 commit comments

Comments
 (0)