Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { combineLatest, defer, of } from 'rxjs';
- import { map, switchMap, tap } from 'rxjs/operators';
- import { AngularFirestore } from 'angularfire2/firestore';
- @Injectable()
- export class RxService {
- constructor(private readonly fireStore: AngularFirestore) {
- }
- public docJoin(paths: { [key: string]: string }) {
- return source =>
- defer(() => {
- let parent;
- const keys = Object.keys(paths);
- return source.pipe(
- switchMap(data => {
- parent = data;
- const docs$ = keys.map(k => {
- const fullPath = `${paths[k]}/${parent[k]}`;
- return this.fireStore.doc(fullPath).valueChanges();
- });
- return combineLatest(docs$);
- }),
- map(arr => {
- const joins = keys.reduce((acc, cur, idx) => {
- return { ...acc, [cur]: arr[idx] };
- }, {});
- return { ...parent, ...joins };
- })
- );
- });
- }
- public leftJoinDocument(field, fieldName, collection) {
- return source =>
- defer(() => {
- let collectionData;
- const cache = new Map();
- return source.pipe(
- switchMap(data => {
- cache.clear();
- collectionData = data as any[];
- const reads$ = [];
- let i = 0;
- for (const doc of collectionData) {
- if (!doc[field] || cache.get(doc[field])) {
- continue;
- }
- reads$.push(
- this.fireStore
- .collection(collection)
- .doc(doc[field])
- .valueChanges()
- );
- cache.set(doc[field], i);
- i++;
- }
- return reads$.length ? combineLatest(reads$) : of([]);
- }),
- map(joins => {
- return collectionData.map((v, i) => {
- const joinIdx = cache.get(v[field]);
- return { ...v, [fieldName]: joins[joinIdx] || null };
- });
- })
- );
- });
- }
- public leftJoin(field, collection, type = 'all', field2 = field) {
- return source =>
- defer(() => {
- let collectionData;
- let totalJoins = 0;
- return source.pipe(
- switchMap(data => {
- collectionData = data as any[];
- const reads$ = [];
- for (const doc of collectionData) {
- if (doc[field] || doc[field2]) {
- let q;
- if (type === 'all') {
- q = ref => ref.where(field, '==', doc[field2]);
- } else if (type === 'event') {
- q = ref => ref.where(field, '==', doc[field2]).where('status', '==', 'approved');
- }
- reads$.push(
- this.fireStore.collection(collection, q).snapshotChanges()
- .pipe(map((snapshot) => {
- return snapshot.map((data) => {
- return {
- id: data.payload.doc.id,
- ...data.payload.doc.data()
- }
- });
- }))
- );
- } else {
- reads$.push(of([]));
- }
- }
- return combineLatest(reads$);
- }),
- map(joins => {
- return collectionData.map((v, i) => {
- totalJoins += joins[i].length;
- return { ...v, ['mazlum']: joins[i] || null };
- });
- }),
- tap(final => {
- // console.log(
- // `Queried ${(final as any).length}, Joined ${totalJoins} docs`
- // );
- totalJoins = 0;
- })
- );
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement