-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathfirestore.ts
173 lines (160 loc) · 6.04 KB
/
firestore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { InjectionToken, NgZone } from '@angular/core';
import { FirebaseFirestore, CollectionReference, DocumentReference } from '@firebase/firestore-types';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
import { from } from 'rxjs/observable/from';
import 'rxjs/add/operator/map';
import { FirebaseOptions } from '@firebase/app-types';
import { Injectable, Inject, Optional } from '@angular/core';
import { QueryFn, AssociatedReference } from './interfaces';
import { AngularFirestoreDocument } from './document/document';
import { AngularFirestoreCollection } from './collection/collection';
import { FirebaseAppConfig, FirebaseAppName, _firebaseAppFactory, FirebaseZoneScheduler } from 'angularfire2';
/**
* The value of this token determines whether or not the firestore will have persistance enabled
*/
export const EnablePersistenceToken = new InjectionToken<boolean>('angularfire2.enableFirestorePersistence');
/**
* A utility methods for associating a collection reference with
* a query.
*
* @param collectionRef - A collection reference to query
* @param queryFn - The callback to create a query
*
* Example:
* const { query, ref } = associateQuery(docRef.collection('items'), ref => {
* return ref.where('age', '<', 200);
* });
*/
export function associateQuery(collectionRef: CollectionReference, queryFn = ref => ref): AssociatedReference {
const query = queryFn(collectionRef);
const ref = collectionRef;
return { query, ref };
}
/**
* AngularFirestore Service
*
* This service is the main entry point for this feature module. It provides
* an API for creating Collection and Reference services. These services can
* then be used to do data updates and observable streams of the data.
*
* Example:
*
* import { Component } from '@angular/core';
* import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
* import { Observable } from 'rxjs/Observable';
* import { from } from 'rxjs/observable/from';
*
* @Component({
* selector: 'app-my-component',
* template: `
* <h2>Items for {{ (profile | async)?.name }}
* <ul>
* <li *ngFor="let item of items | async">{{ item.name }}</li>
* </ul>
* <div class="control-input">
* <input type="text" #itemname />
* <button (click)="addItem(itemname.value)">Add Item</button>
* </div>
* `
* })
* export class MyComponent implements OnInit {
*
* // services for data operations and data streaming
* private readonly itemsRef: AngularFirestoreCollection<Item>;
* private readonly profileRef: AngularFirestoreDocument<Profile>;
*
* // observables for template
* items: Observable<Item[]>;
* profile: Observable<Profile>;
*
* // inject main service
* constructor(private readonly afs: AngularFirestore) {}
*
* ngOnInit() {
* this.itemsRef = afs.collection('items', ref => ref.where('user', '==', 'davideast').limit(10));
* this.items = this.itemsRef.valueChanges().map(snap => snap.docs.map(data => doc.data()));
* // this.items = from(this.itemsRef); // you can also do this with no mapping
*
* this.profileRef = afs.doc('users/davideast');
* this.profile = this.profileRef.valueChanges();
* }
*
* addItem(name: string) {
* const user = 'davideast';
* this.itemsRef.add({ name, user });
* }
* }
*/
@Injectable()
export class AngularFirestore {
public readonly firestore: FirebaseFirestore;
public readonly persistenceEnabled$: Observable<boolean>;
public readonly scheduler: FirebaseZoneScheduler;
/**
* Each Feature of AngularFire has a FirebaseApp injected. This way we
* don't rely on the main Firebase App instance and we can create named
* apps and use multiple apps.
* @param app
*/
constructor(
@Inject(FirebaseAppConfig) config:FirebaseOptions,
@Optional() @Inject(FirebaseAppName) name:string,
@Optional() @Inject(EnablePersistenceToken) shouldEnablePersistence: boolean,
zone: NgZone
) {
this.scheduler = new FirebaseZoneScheduler(zone);
this.firestore = zone.runOutsideAngular(() => {
const app = _firebaseAppFactory(config, name);
return app.firestore();
});
this.persistenceEnabled$ = zone.runOutsideAngular(() => {
return shouldEnablePersistence ?
from(this.firestore.enablePersistence().then(() => true, () => false)) :
from(new Promise((res, rej) => { res(false); }));
});
}
/**
* Create a reference to a Firestore Collection based on a path or
* CollectionReference and an optional query function to narrow the result
* set.
* @param pathOrRef
* @param queryFn
*/
collection<T>(path: string, queryFn?: QueryFn): AngularFirestoreCollection<T>
collection<T>(ref: CollectionReference, queryFn?: QueryFn): AngularFirestoreCollection<T>
collection<T>(pathOrRef: string | CollectionReference, queryFn?: QueryFn): AngularFirestoreCollection<T> {
let collectionRef: CollectionReference;
if (typeof pathOrRef === 'string') {
collectionRef = this.firestore.collection(pathOrRef);
} else {
collectionRef = pathOrRef;
}
const { ref, query } = associateQuery(collectionRef, queryFn);
return new AngularFirestoreCollection<T>(ref, query, this);
}
/**
* Create a reference to a Firestore Document based on a path or
* DocumentReference. Note that documents are not queryable because they are
* simply objects. However, documents have sub-collections that return a
* Collection reference and can be queried.
* @param pathOrRef
*/
doc<T>(path: string): AngularFirestoreDocument<T>
doc<T>(ref: DocumentReference): AngularFirestoreDocument<T>
doc<T>(pathOrRef: string | DocumentReference): AngularFirestoreDocument<T> {
let ref: DocumentReference;
if (typeof pathOrRef === 'string') {
ref = this.firestore.doc(pathOrRef);
} else {
ref = pathOrRef;
}
return new AngularFirestoreDocument<T>(ref, this);
}
/**
* Returns a generated Firestore Document Id.
*/
createId() {
return this.firestore.collection('_').doc().id
}
}