This repository was archived by the owner on May 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathfirebase-firestore-mixin.html
More file actions
317 lines (283 loc) · 10.4 KB
/
firebase-firestore-mixin.html
File metadata and controls
317 lines (283 loc) · 10.4 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<link rel="import" href="firebase-firestore-script.html">
<script>
if (typeof Polymer === 'undefined') {
throw new Error('Polymer.FirestoreMixin must be imported after Polymer itself.');
}
{
const CONSTRUCTOR_TOKEN = Symbol('polymerfire-firestore-mixin-constructor');
const CONNECTED_CALLBACK_TOKEN =
Symbol('polymerfire-firestore-mixin-connected-callback');
const PROPERTY_BINDING_REGEXP = /{([^{]+)}/g;
const isOdd = (x) => x & 1 === 1;
const parsePath = (path) => {
const parts = path.split(PROPERTY_BINDING_REGEXP);
let literals = [], props = [];
parts.forEach((part, index) => {
(isOdd(index) ? props : literals).push(part);
})
return {literals, props};
}
const stitch = (literals, values) => {
let whole = '';
for (var i = 0; i < literals.length; i++) {
whole += literals[i];
whole += values[i] || '';
}
return whole;
}
const collect = (what, which) => {
let res = {};
while (what) {
res = Object.assign({}, what[which], res); // Respect prototype priority
what = Object.getPrototypeOf(what);
}
return res;
};
const iDoc = (snap) => {
if (snap.exists) {
return Object.assign({__id__: snap.id}, snap.data());
} else {
return null;
}
}
const TRANSFORMS = {
doc: iDoc,
collection: (snap) => snap.empty ? [] : snap.docs.map(iDoc),
}
/**
* This mixin provides bindings to documents and collections in a
* Cloud Firestore database through special property declarations.
*
* ### Basic Usage
*
* ```js
* class MyElement extends Polymer.FirestoreMixin(Polymer.Element) {
* // ...
* static get properties() {
* return {
* uid: String,
* user: {
* type: Object,
* doc: 'users/{uid}'
* },
* messages: {
* type: Array,
* collection: 'users/{uid}/messages'
* }
* }
* }
* }
* ```
*
* As you can see, specific properties have been decorated with `doc` and
* `collection` options. These options provide full paths to documents or
* collections in your Firestore database. When templatized with curly
* braces (e.g. `{uid}` above), the data will be dynamically rebound as
* the templatized properties change.
*
* PolymerFirestore bindings are **intentionally read-only**. Automatic
* three-way binding (i.e. syncing changes from the element back up to
* the database) are great for toy apps but largely an antipattern.
*
* In addition to loading data into the specified property, PolymerFirestore
* also makes additional convenience properties:
*
* * `<propname>Ref`: a Firestore reference to the doc/collection
* * `<propname>Ready`: will be true when all path segments are present and data has been fetched at least once
*
* ### Querying
*
* PolymerFire supports querying by supplying a builder function to the
* `query` option. The function will be bound to the element and called with
* the ref and element instance. For example:
*
* ```js
* {
* uid: String,
* label: String,
* category: String,
* notes: {
* type: Array,
* collection: 'users/{uid}/notes',
* query: (q, el) => {
* q = q.orderBy('date', 'desc').limit(100)
* if (el.color) { q.where('color','==', el.color) }
* if (el.category) { q.where('category', '==', el.category) }
* return q;
* },
* observes: ['color', 'category']
* }
* }
* ```
*
* In the above example, a rich query is further filtered down by other
* properties on the element. Remember to declare each query-affecting
* property in your `observes` option.
*
* ### Options
*
* * **doc:** *string*, the full (optionally templatized) path to a document.
* Property type must be defined as `Object`
* * **collection:** *string*, the full (optionally templatized) path to
* a collection. Property type must be defined as `Array`.
* * **live:** *boolean*, whether or not to continue updating the property
* as data changes in the database. If persistence is enabled, value of
* a property might be assigned twice (first from cache, then a live copy).
* See `noCache` if you wan't to change this behavior.
* * **query:** *(ref: CollectionReference, el: Polymer.Element): Query*
* a query builder function that takes the computed collection reference and
* the element instance. It must return an instance of Query.
* * **observes:** a list of properties which, if changed, should trigger
* a rebuild of a listener.
* * **noCache:** cached Firestore data won't be assigned to a property
* value even if persistence is enabled.
*
* @polymer
* @mixinFunction Polymer.FirestoreMixin
*/
Polymer.FirestoreMixin = parent =>
class extends parent {
static _assertPropertyTypeCorrectness(prop) {
const errorMessage = (listenerType, propertyType) =>
`FirestoreMixin's ${listenerType} can only be used with properties ` +
`of type ${propertyType}.`;
const assert = (listenerType, propertyType) => {
if (prop[listenerType] !== undefined && prop.type !== propertyType) {
throw new Error(errorMessage(listenerType, propertyType.name));
}
}
assert('doc', Object);
assert('collection', Array);
}
constructor() {
super();
if (this[CONSTRUCTOR_TOKEN] === true) {
return;
}
this[CONSTRUCTOR_TOKEN] = true;
this._firestoreProps = {};
this._firestoreListeners = {};
}
connectedCallback() {
if (this[CONNECTED_CALLBACK_TOKEN] !== true) {
this[CONNECTED_CALLBACK_TOKEN] = true;
this.db = this.constructor.db || firebase.firestore();
this.db.settings({timestampsInSnapshots: true});
const props = collect(this.constructor, 'properties');
Object
.values(props)
.forEach(this.constructor._assertPropertyTypeCorrectness);
for (let name in props) {
const options = props[name];
if (options.doc || options.collection) {
this._firestoreBind(name, options);
}
}
}
super.connectedCallback();
}
_firestoreBind(name, options) {
const defaults = {
live: false,
observes: [],
}
const parsedPath = parsePath(options.doc || options.collection);
const config = Object.assign({}, defaults, options, parsedPath);
const type = config.type =
config.doc ? 'doc' : config.collection ? 'collection' : undefined;
this._firestoreProps[name] = config;
const args = config.props.concat(config.observes);
if (args.length > 0) {
// Create a method observer that will be called every time
// a templatized or observed property changes
const observer =
`_firestoreUpdateBinding('${name}', ${args.join(',')})`
this._createMethodObserver(observer);
}
this._firestoreUpdateBinding(name, ...args.map(x => this[x]));
}
_firestoreUpdateBinding(name, ...args) {
this._firestoreUnlisten(name);
const config = this._firestoreProps[name];
const isDefined = (x) => x !== undefined;
const propArgs = args.slice(0, config.props.length).filter(isDefined);
const observesArgs = args.slice(config.props.length).filter(isDefined);
const propArgsReady = propArgs.length === config.props.length;
const observesArgsReady =
observesArgs.length === config.observes.length;
if (propArgsReady && observesArgsReady) {
const collPath = stitch(config.literals, propArgs);
const assigner = this._firestoreAssigner(name, config);
let ref = this.db[config.type](collPath);
this[name + 'Ref'] = ref;
if (config.query) {
ref = config.query.call(this, ref, this);
}
this._firestoreListeners[name] = ref.onSnapshot(assigner);
}
}
_firestoreUnlisten(name, type) {
if (this._firestoreListeners[name]) {
this._firestoreListeners[name]();
delete this._firestoreListeners[name];
}
this.setProperties({
[name]: type === 'collection' ? [] : null,
[name + 'Ref']: null,
[name + 'Ready']: false,
})
}
_firestoreAssigner(name, {type, live, noCache}) {
const makeAssigner = (assigner) => (snap) => {
const shouldAssign =
noCache !== true || snap.metadata.fromCache === false;
if (shouldAssign) {
assigner.call(this, name, snap);
this[name + 'Ready'] = true;
if (live !== true) {
this._firestoreListeners[name]();
}
}
}
if (type === 'doc') {
return makeAssigner(this._firestoreAssignDocument);
} else if (type === 'collection') {
return makeAssigner(this._firestoreAssignCollection);
} else {
throw new Error('Unknown listener type.');
}
}
_firestoreAssignDocument(name, snap) {
this[name] = iDoc(snap);
}
_firestoreAssignCollection(name, snap) {
const propertyValueIsArray = Array.isArray(this[name])
const allDocumentsChanged = snap.docs.length === snap.docChanges.length;
if (propertyValueIsArray && allDocumentsChanged === false) {
snap.docChanges.forEach((change) => {
switch (change.type) {
case 'added':
this.splice(name, change.newIndex, 0, iDoc(change.doc));
break;
case 'removed':
this.splice(name, change.oldIndex, 1);
break;
case 'modified':
if (change.oldIndex === change.newIndex) {
this.splice(name, change.oldIndex, 1, iDoc(change.doc));
} else {
this.splice(name, change.oldIndex, 1);
this.splice(name, change.newIndex, 0, iDoc(change.doc));
}
break;
default:
throw new Error(`Unhandled document change: ${change.type}.`);
}
});
} else {
this[name] = snap.docs.map(iDoc);
}
}
}
}
</script>