@@ -4,8 +4,12 @@ DocumentSnapshot.prototype.data = function () {
44 return this . _document
55}
66
7- let id = 0
8- class Key {
7+ export { DocumentSnapshot }
8+
9+ const noop = _ => null
10+
11+ export let id = 0
12+ export class Key {
913 constructor ( ) {
1014 this . id = id ++
1115 }
@@ -17,22 +21,97 @@ class Key {
1721 }
1822}
1923
20- export const collection = {
21- data : [ ] ,
24+ class DocumentReference {
25+ constructor ( { collection, id, data, index } ) {
26+ this . collection = collection
27+ this . id = id
28+ this . data = data
29+ this . index = index
30+ }
31+
32+ async delete ( ) {
33+ return this . collection . _remove ( this . id )
34+ }
35+
36+ async update ( data ) {
37+ Object . assign ( this . data , data )
38+ return this . collection . _modify ( this . id , this . data )
39+ }
40+ }
41+
42+ class CollectionReference {
43+ constructor ( ) {
44+ this . data = { }
45+ this . cb = this . onError = noop
46+ }
47+
2248 onSnapshot ( cb , onError ) {
2349 this . cb = cb
2450 this . onError = onError
25- } ,
51+ }
2652
27- add ( item ) {
28- this . data . push ( item )
53+ async add ( data ) {
54+ const id = new Key ( )
55+ this . data [ id ] = new DocumentReference ( {
56+ collection : this ,
57+ id,
58+ data,
59+ index : Object . keys ( this . data ) . length
60+ } )
2961 this . cb ( {
3062 docChanges : [ {
31- doc : new DocumentSnapshot ( null , new Key ( ) , item ) , // TODO docsnapshot
32- newIndex : this . data . length - 1 ,
33- oldIndex : - 1 ,
3463 type : 'added' ,
64+ doc : new DocumentSnapshot ( null , id , data ) ,
65+ newIndex : Object . keys ( this . data ) . length ,
66+ oldIndex : - 1 ,
67+ } ]
68+ } )
69+ return this . data [ id ]
70+ }
71+
72+ doc ( id ) {
73+ id = id || new Key ( )
74+ return this . data [ id ] = this . data [ id ] || new DocumentReference ( {
75+ collection : this ,
76+ id,
77+ data : { } ,
78+ index : Object . keys ( this . data ) . length
79+ } )
80+ }
81+
82+ async _remove ( id ) {
83+ const ref = this . data [ id ]
84+ delete this . data [ id ]
85+ this . cb ( {
86+ docChanges : [ {
87+ doc : new DocumentSnapshot ( null , id , ref . data ) ,
88+ type : 'removed' ,
89+ } ]
90+ } )
91+ ref . collection = null
92+ ref . data = null
93+ }
94+
95+ async _modify ( id , data ) {
96+ this . cb ( {
97+ docChanges : [ {
98+ type : 'modified' ,
99+ doc : new DocumentSnapshot ( null , id , data ) ,
100+ oldIndex : this . data [ id ] . index ,
101+ newIndex : this . data [ id ] . index ,
35102 } ]
36103 } )
104+
105+ }
106+ }
107+
108+ export const db = {
109+ db : { } ,
110+ n : 0 ,
111+
112+ collection ( name ) {
113+ // create a collection if no name provided
114+ name = name || `random__${ this . n ++ } `
115+ return db [ name ] = db [ name ] || new CollectionReference ( )
37116 }
38117}
0 commit comments