forked from lsoaresesilva/angularfire-document-mapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.ts
More file actions
500 lines (434 loc) · 14.1 KB
/
document.ts
File metadata and controls
500 lines (434 loc) · 14.1 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
import { throws } from 'assert';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable, forkJoin } from 'rxjs';
import { AppInjector } from './app-injector';
import { FireStoreDocument } from './firestoreDocument';
import Query from './query';
import * as firebase from 'firebase';
export default class DocumentNotFoundError extends Error {}
export function Collection(nome) {
return function (target) {
target.__name = nome;
// target["__name"] = nome;
Object.assign(target, {
__name: nome,
});
};
}
/**
* Formato: name e type
* @param data
*/
export function oneToOne(data) {
function actualDecorator(target, property: string | symbol): void {
if (target.__oneToOne == undefined) {
Object.defineProperty(target, '__oneToOne', {
value: [],
writable: true,
enumerable: true,
});
}
target.__oneToOne.push({ property: property, foreignKeyName: data.name, type: data.type });
}
// return the decorator
return actualDecorator;
}
export function ignore() {
function actualDecorator(target, property: string | symbol): void {
if (target.__ignore == undefined) {
Object.defineProperty(target, '__ignore', {
value: [],
writable: true,
enumerable: true,
});
}
target.__ignore.push(property);
}
// return the decorator
return actualDecorator;
}
export function date() {
function actualDecorator(target, property: string | symbol): void {
if (target.__ignore == undefined) {
Object.defineProperty(target, '__date', {
value: [],
writable: true,
enumerable: true,
});
}
target.property = '';
target.__date.push(property);
}
// return the decorator
return actualDecorator;
}
/*
export function lazy() {
function actualDecorator(target, property: string | symbol): void {
if (target.__ignore == undefined)
Object.defineProperty(target, '__lazy', {
value: [],
writable: true,
enumerable: true
})
target.property = "";
target.__lazy.push(property);
}
return actualDecorator;
}
* This class is used to intercept a call to an attribute. When a property is marked as @lazy they will be retrivied from document only when needed.
*
class ExtendableProxy {
constructor() {
return new Proxy(this, {
get: function(obj, prop, receiver) {
if( obj["__lazy"] != undefined && obj[prop] == undefined){
let isLazy = false;
obj["__lazy"].forEach(property=>{
if(prop == property)
isLazy = true;
})
let func = obj["getLazy"];
if(isLazy && typeof func !== "undefined"){
let r = null;
let o = null;
return new Observable(observer=>{
o = observer;
obj["getLazy"]().subscribe(resultado=>{
observer.next(resultado);
observer.complete();
}, err=>{
observer.error(err);
});
}).subscribe(res=>{
o.next(res);
o.complete();
})
}
}
return obj[prop];
}
});
}
}*/
export class Document {
constructor(protected id) {
this.db = AppInjector.get(AngularFirestore);
/*const settings = { experimentalForceLongPolling: true };
this.db.firestore.app.firestore().settings( settings );*/
this.constructDateObjects();
}
db: AngularFirestore;
static getAngularFirestore() {
return AppInjector.get(AngularFirestore);
}
static getDaysInterval = function (start, end): any[] {
const datas = [];
for (const dt = new Date(start); dt <= end; dt.setDate(dt.getDate() + 1)) {
datas.push(new Date(dt));
}
return datas;
};
static filterDocumentsByDate(documents, dateField, start, end) {
const filteredDocuments = [];
if (Array.isArray(documents) && documents.length > 0) {
const dateInterval = this.getDaysInterval(end, start);
dateInterval.forEach((data) => {
documents.forEach((document) => {
const date = document[dateField].toDate();
if (date.toDateString() === data.toDateString()) {
filteredDocuments.push(document);
}
});
});
}
return filteredDocuments;
}
static getByQuery(query, orderBy = null):Observable<any> {
return new Observable((observer) => {
this.getAll(query, orderBy).subscribe(
(resultado) => {
if (resultado.length > 0) {
observer.next(resultado[0]);
observer.complete();
} else {
observer.next(null);
observer.complete();
}
},
(err) => {
observer.error(err);
}
);
});
}
/**
* Get a document from collection.
* @param id
* @returns Observable containing the document; or error if document does not exists.
*/
static get(id):Observable<any> {
if (id == null || id == undefined) {
throw new Error('ID não posse ser vazio.');
}
const db = this.getAngularFirestore();
Document.prerequisitos(this['__name'], db);
return new Observable((observer) => {
const n = this['__name'];
const document: any = db.doc<any>(this['__name'] + '/' + id);
document.get({ source: 'server' }).subscribe((result) => {
try {
observer.next(new FireStoreDocument(result).toObject(this['prototype']));
observer.complete();
} catch (e) {
observer.error(
new Error('Document not found. Collection: ' + this['__name'] + '. ID: ' + id)
);
} finally {
}
});
});
}
static search(query:Query){
return new Observable((observer) => {
const db = this.getAngularFirestore();
const objetos = [];
const collection = db.collection(this['__name'], (ref) => ref.orderBy(query.column).startAt(query.value).endAt(query.value+"\uf8ff"));
collection.get({ source: 'server' }).subscribe(
(resultados) => {
const i = 0;
resultados.docs.forEach((document) => {
objetos.push(new FireStoreDocument(document).toObject(this['prototype']));
});
observer.next(objetos);
observer.complete();
},
(err) => {
observer.error(err);
}
);
});
}
static buildCollection(db, collectionName, query, orderByParam = null) {
let collection: any = db.collection(collectionName);
if (query != null) {
// collection = db.collection(collectionName, ref=>ref.where(query.column, query.operator, query.value));
if (orderByParam != null) {
collection = db.collection(collectionName, (ref) =>
Query.build(ref, query).orderBy(orderByParam)
);
} else {
collection = db.collection(collectionName, (ref) => Query.build(ref, query));
}
} else if (orderByParam != null) {
collection = db.collection(collectionName, (ref) => ref.orderBy(orderByParam));
}
return collection;
}
static count() {
return new Observable((observer) => {
const count = 0;
this.getAll().subscribe(
(results) => {
observer.next(results.length);
observer.complete();
},
(err) => {
observer.error(err);
}
);
});
}
static exportToJson(){
let json = {};
return new Observable(observer=>{
this.getAll().subscribe(documents=>{
json[this['__name']] = [];
documents.forEach(document=>{
json[this['__name']].push(document.toJson());
})
observer.next(JSON.stringify(json));
observer.complete()
})
})
}
static getAll(query = null, orderBy = null): Observable<any[]> {
const db = this.getAngularFirestore();
const objetos = [];
Document.prerequisitos(this['__name'], db);
// TODO: migrar os códigos acima para dentro do observable, em um try/catch e no catch, em caso de erro, lançar um observer.error
return new Observable((observer) => {
// let collection: any = this.buildCollection(db, this["__name"], null);
const collection = this.buildCollection(db, this['__name'], query, orderBy);
collection.get({ source: 'server' }).subscribe(
(resultados) => {
const i = 0;
resultados.docs.forEach((document) => {
objetos.push(new FireStoreDocument(document).toObject(this['prototype']));
});
observer.next(objetos);
observer.complete();
},
(err) => {
observer.error(err);
}
);
});
}
// TODO: incluir a opção de deletar por query
static deleteAll() {
const db = this.getAngularFirestore();
Document.prerequisitos(this['__name'], db);
return new Observable((observer) => {
let counter = 0;
this.getAll().subscribe(
(resultados) => {
const documents = [];
resultados.forEach((documento) => {
counter++;
documents.push(this.delete(documento.id));
});
if (documents.length > 0) {
forkJoin(documents).subscribe((resultado) => {
observer.next(resultado.length);
observer.complete();
});
} else {
observer.next(counter);
observer.complete();
}
},
(err) => {
observer.error(err);
}
);
});
}
static delete(id) {
const db = this.getAngularFirestore();
Document.prerequisitos(this['__name'], db);
return new Observable((observer) => {
const collection: AngularFirestoreCollection<any> = db.collection<any>(this['__name']);
collection
.doc(id)
.delete()
.then((resultado) => {
observer.next(true);
observer.complete();
})
.catch((err) => {
observer.next(false);
observer.complete();
});
});
}
/**
* Verifica se os pré-requisitos para execução de uma operação no Firestore estão sendo atendidos. Os pré-requisitos estabelecidos são: nome da collection e instância do AngularFirestore
* @param __name nome da collection
* @param db instância de AngularFirestore
*/
static prerequisitos(__name, db) {
if (__name == undefined || __name == null) {
throw new Error('Não foi atribuído um nome para essa collection.');
}
if (db == undefined || db == null) {
throw new Error('Não há uma instância de AngularFirestore.');
}
}
/**
* @date annotation does not create date properties in Documents child's class. This method create those properties (empty as they will be populated when sent to database).
*/
constructDateObjects() {
if (this['__date'] != undefined && this['__date'].length > 0) {
this['__date'].forEach((dateObject) => {
this[dateObject] = '';
});
}
}
/**
* Retrievies the primary key of this document.
*/
pk() {
return this.id;
}
objectToDocument() {
const object = {};
const x = Reflect.ownKeys(this);
Reflect.ownKeys(this).forEach((propriedade) => {
const propriedadesIgnoradas = this['__ignore'];
if (
typeof this[propriedade] != 'function' &&
typeof this[propriedade] != 'undefined' /* && typeof this[propriedade] != "object"*/
) {
if (
this['__ignore'] == undefined ||
(this['__ignore'] != undefined && !this['__ignore'].includes(propriedade))
) {
if (this['__date'] != undefined && this['__date'].includes(propriedade)) {
object[propriedade] = firebase.firestore.FieldValue.serverTimestamp();
} else {
// aqui usar o __oneToOne
const tipo = typeof this[propriedade];
if (typeof this[propriedade] == 'object') {
if (this['__oneToOne'] != undefined && this['__oneToOne'].length > 0) {
for (let i = 0; i < this['__oneToOne'].length; i++) {
if (
this['__oneToOne'][i].property == propriedade &&
typeof this[propriedade].pk === 'function'
) {
object[this['__oneToOne'][i].foreignKeyName] = this[propriedade].pk();
break;
}
}
}
} else {
object[propriedade] = this[propriedade];
}
}
}
}
});
if (this.id != undefined) {
object['id'] = this.id;
}
return object;
}
save(): Observable<any> {
Document.prerequisitos(this.constructor['__name'], this.db);
const ___this = this;
return new Observable((observer) => {
try {
const document = ___this.objectToDocument();
if (document['id'] != undefined) {
const docRef = this.db.collection<any>(this.constructor['__name']).doc(document['id']);
delete document['id']; // id cannot be in the document, as it isnt an attribute.
docRef
.update(document)
.then((result) => {
observer.next(___this);
observer.complete();
})
.catch((err) => {
observer.error(err);
});
} else {
const collection: AngularFirestoreCollection<any> = this.db.collection<any>(
this.constructor['__name']
);
collection
.add(document)
.then((result) => {
___this.id = result.id;
observer.next(___this);
observer.complete();
})
.catch((err) => {
observer.error(err);
});
}
} catch (err) {
observer.error(err);
}
});
}
}