|
2 | 2 | * @flow |
3 | 3 | */ |
4 | 4 | import Reference from './reference.js'; |
| 5 | +import { isObject, deepGet } from './../../utils'; |
5 | 6 |
|
6 | 7 | export default class Snapshot { |
7 | 8 | static key: String; |
8 | 9 | static value: Object; |
9 | 10 | static exists: boolean; |
10 | 11 | static hasChildren: boolean; |
11 | | - static childrenCount: Number; |
12 | 12 | static childKeys: String[]; |
13 | 13 |
|
14 | 14 | ref: Object; |
15 | 15 | key: string; |
16 | 16 | value: any; |
17 | 17 | exists: boolean; |
18 | 18 | priority: any; |
19 | | - hasChildren: boolean; |
20 | | - childrenCount: number; |
21 | 19 | childKeys: Array<string>; |
22 | 20 |
|
23 | 21 | constructor(ref: Reference, snapshot: Object) { |
24 | 22 | this.ref = ref; |
25 | 23 | this.key = snapshot.key; |
26 | 24 | this.value = snapshot.value; |
27 | 25 | 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; |
31 | 27 | this.childKeys = snapshot.childKeys || []; |
32 | 28 | } |
| 29 | + /* |
| 30 | + * DEFAULT API METHODS |
| 31 | + */ |
33 | 32 |
|
34 | 33 | val() { |
35 | 34 | return this.value; |
36 | 35 | } |
37 | 36 |
|
| 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 | + |
38 | 52 | 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; |
41 | 71 | } |
42 | 72 |
|
| 73 | + /* |
| 74 | + * EXTRA API METHODS |
| 75 | + */ |
43 | 76 | map(fn: (key: string) => mixed) { |
44 | 77 | const arr = []; |
45 | | - this.forEach(item => arr.push(fn(item))); |
| 78 | + this.forEach((item, i) => arr.push(fn(item, i))); |
46 | 79 | return arr; |
47 | 80 | } |
48 | 81 |
|
|
0 commit comments