-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdocument.ts
More file actions
641 lines (538 loc) · 17.6 KB
/
document.ts
File metadata and controls
641 lines (538 loc) · 17.6 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable, forkJoin, Subject, observable } from 'rxjs';
import { AppInjector } from './app-injector';
import { FireStoreDocument } from './firestoreDocument';
import Query from './query';
import * as firebase from 'firebase';
import DocumentTest, { DocumentSalvo } from './documentTest';
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 = '';
if (target.__date != null) {
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(public id) {
this.init();
/*const settings = { experimentalForceLongPolling: true };
this.db.firestore.app.firestore().settings( settings );*/
}
static isModoTeste = false;
static documentTeste:DocumentTest = new DocumentTest();
db: AngularFirestore;
doc; // Reference to the document
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 onDocumentUpdate(id, callback:Subject<any>){
const db = this.getAngularFirestore();
Document.prerequisitos(this['__name'], db);
const n = this['__name'];
const document: any = db.doc<any>(this['__name'] + '/' + id);
document.snapshotChanges().subscribe(snapshot=>{
let object = new FireStoreDocument(snapshot).toObject(this['prototype']);
callback.next(object);
//callback.complete();
});
/* document.get({ source: 'server' }).subscribe((result) => {
try {
let retrievedDocument = new FireStoreDocument(result).toObject(this['prototype']);
observer.next(retrievedDocument);
observer.complete();
} catch (e) {
observer.error(
new Error('Document not found. Collection: ' + this['__name'] + '. ID: ' + id)
);
} finally {
}
});
});
this.get(id).subscribe(object=>{
object.doc.onSnapshot(snapshot=>{
callback.next(snapshot);
callback.complete();
})
}) */
}
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 {
let retrievedDocument = new FireStoreDocument(result).toObject(this['prototype']);
observer.next(retrievedDocument);
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(data_inicio=null, data_fim=null):Observable<string>{
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 exportToJsonFiltroData(data_inicio=null, data_fim=null):Observable<string>{
let json = {};
return new Observable(observer=>{
this.exportGetAll().subscribe(documents=>{
json[this['__name']] = [];
documents.forEach(document=>{
json[this['__name']].push(document.toJson());
})
observer.next(JSON.stringify(json));
observer.complete()
})
})
}
static exportGetAll(query = null, orderBy = null): Observable<any[]> {
return new Observable(observer=>{
const db = this.getAngularFirestore();
const objetos = [];
let collection = db.collection(this['__name'], (ref) => ref.orderBy("data").startAfter(new Date("2021-11-07")).endBefore(new Date("2021-12-31")));
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 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.');
}
}
static rastrearPersistencia(){
this.isModoTeste = true;
}
static batchSave(objects:Document[]):Observable<any>{
return new Observable(observable=>{
if(Array.isArray(objects)){
const multipleSaveRequest = [];
objects.forEach(object=>{
multipleSaveRequest.push(object.save());
});
forkJoin(multipleSaveRequest).subscribe(results=>{
observable.next(results);
observable.complete();
})
}
})
}
/**
* @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] = '';
});
}
}
init(){
if(this.db == null){
this.db = AppInjector.get(AngularFirestore);
}
this.constructDateObjects();
}
/**
* 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;
}
/**
* Called right before the instance is converted to Firestore document and saved in the database.
*/
priorToSave() {
}
save(): Observable<any> {
Document.prerequisitos(this.constructor['__name'], this.db);
const ___this = this;
return new Observable((observer) => {
try {
this.priorToSave();
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;
if (Document.isModoTeste) {
let documentSalvo:DocumentSalvo = {
nomeColecao:this.constructor['__name'],
id:result.id
}
Document.documentTeste.incluirDocument(documentSalvo);
}
observer.next(___this);
observer.complete();
})
.catch((err) => {
observer.error(err);
});
}
} catch (err) {
observer.error(err);
}
});
}
}