├── src
├── assets
│ └── .gitkeep
├── app
│ ├── app.component.scss
│ ├── app-routing.module.ts
│ ├── app.component.html
│ ├── app.module.ts
│ ├── app.component.ts
│ ├── app.component.spec.ts
│ ├── docJoin.ts
│ └── collectionJoin.ts
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── favicon.ico
├── styles.scss
├── tsconfig.app.json
├── tsconfig.spec.json
├── tslint.json
├── browserslist
├── main.ts
├── index.html
├── test.ts
├── karma.conf.js
└── polyfills.ts
├── e2e
├── src
│ ├── app.po.ts
│ └── app.e2e-spec.ts
├── tsconfig.e2e.json
└── protractor.conf.js
├── .editorconfig
├── tsconfig.json
├── .gitignore
├── package.json
├── README.md
├── tslint.json
└── angular.json
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/app.component.scss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AngularFirebase/133-firestore-joins-custom-rx-operators/HEAD/src/favicon.ico
--------------------------------------------------------------------------------
/src/styles.scss:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
3 | .content {
4 | display: flex;
5 | flex-direction: column;
6 | padding: 5vh 10vw;
7 | }
--------------------------------------------------------------------------------
/src/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/app",
5 | "types": []
6 | },
7 | "exclude": [
8 | "test.ts",
9 | "**/*.spec.ts"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo() {
5 | return browser.get('/');
6 | }
7 |
8 | getParagraphText() {
9 | return element(by.css('app-root h1')).getText();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/e2e/tsconfig.e2e.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/app",
5 | "module": "commonjs",
6 | "target": "es5",
7 | "types": [
8 | "jasmine",
9 | "jasminewd2",
10 | "node"
11 | ]
12 | }
13 | }
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/src/app/app-routing.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { Routes, RouterModule } from '@angular/router';
3 |
4 | const routes: Routes = [];
5 |
6 | @NgModule({
7 | imports: [RouterModule.forRoot(routes)],
8 | exports: [RouterModule]
9 | })
10 | export class AppRoutingModule { }
11 |
--------------------------------------------------------------------------------
/src/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "test.ts",
12 | "polyfills.ts"
13 | ],
14 | "include": [
15 | "**/*.spec.ts",
16 | "**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 |
3 | describe('workspace-project App', () => {
4 | let page: AppPage;
5 |
6 | beforeEach(() => {
7 | page = new AppPage();
8 | });
9 |
10 | it('should display welcome message', () => {
11 | page.navigateTo();
12 | expect(page.getParagraphText()).toEqual('Welcome to baseSimple!');
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/src/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "app",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "app",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/browserslist:
--------------------------------------------------------------------------------
1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed
5 | > 0.5%
6 | last 2 versions
7 | Firefox ESR
8 | not dead
9 | # IE 9-11
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.log(err));
13 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "outDir": "./dist/out-tsc",
6 | "sourceMap": true,
7 | "declaration": false,
8 | "module": "es2015",
9 | "moduleResolution": "node",
10 | "emitDecoratorMetadata": true,
11 | "experimentalDecorators": true,
12 | "target": "es5",
13 | "typeRoots": [
14 | "node_modules/@types"
15 | ],
16 | "lib": [
17 | "es2017",
18 | "dom"
19 | ]
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | BaseSimple
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 |
8 | # dependencies
9 | /node_modules
10 |
11 | # IDEs and editors
12 | /.idea
13 | .project
14 | .classpath
15 | .c9/
16 | *.launch
17 | .settings/
18 | *.sublime-workspace
19 |
20 | # IDE - VSCode
21 | .vscode/*
22 | !.vscode/settings.json
23 | !.vscode/tasks.json
24 | !.vscode/launch.json
25 | !.vscode/extensions.json
26 |
27 | # misc
28 | /.sass-cache
29 | /connect.lock
30 | /coverage
31 | /libpeerconnection.log
32 | npm-debug.log
33 | yarn-error.log
34 | testem.log
35 | /typings
36 |
37 | # System Files
38 | .DS_Store
39 | Thumbs.db
40 |
--------------------------------------------------------------------------------
/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * In development mode, for easier debugging, you can ignore zone related error
11 | * stack frames such as `zone.run`/`zoneDelegate.invokeTask` by importing the
12 | * below file. Don't forget to comment it out in production mode
13 | * because it will have a performance impact when errors are thrown
14 | */
15 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
16 |
--------------------------------------------------------------------------------
/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: any;
11 |
12 | // First, initialize the Angular testing environment.
13 | getTestBed().initTestEnvironment(
14 | BrowserDynamicTestingModule,
15 | platformBrowserDynamicTesting()
16 | );
17 | // Then we find all the tests.
18 | const context = require.context('./', true, /\.spec\.ts$/);
19 | // And load the modules.
20 | context.keys().map(context);
21 |
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 | Document JOIN Document(s)
2 |
3 |
4 | {{ item.key }}: {{ item.value | json }}
5 |
6 |
7 |
8 |
9 | Collection JOIN Collection by Field (Inner Join)
10 |
11 |
12 |
13 |
{{ doc.name }}
14 |
15 |
16 | {{ item.key }}: {{ item.value | json }}
17 |
18 |
19 |
20 |
21 |
22 |
23 | Collection JOIN Documents
24 |
25 |
26 |
27 |
{{ doc.name }}
28 |
29 |
30 | {{ item.key }}: {{ item.value | json }}
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // Protractor configuration file, see link for more information
2 | // https://github.com/angular/protractor/blob/master/lib/config.ts
3 |
4 | const { SpecReporter } = require('jasmine-spec-reporter');
5 |
6 | exports.config = {
7 | allScriptsTimeout: 11000,
8 | specs: [
9 | './src/**/*.e2e-spec.ts'
10 | ],
11 | capabilities: {
12 | 'browserName': 'chrome'
13 | },
14 | directConnect: true,
15 | baseUrl: 'http://localhost:4200/',
16 | framework: 'jasmine',
17 | jasmineNodeOpts: {
18 | showColors: true,
19 | defaultTimeoutInterval: 30000,
20 | print: function() {}
21 | },
22 | onPrepare() {
23 | require('ts-node').register({
24 | project: require('path').join(__dirname, './tsconfig.e2e.json')
25 | });
26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
27 | }
28 | };
--------------------------------------------------------------------------------
/src/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../coverage'),
20 | reports: ['html', 'lcovonly'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false
30 | });
31 | };
--------------------------------------------------------------------------------
/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserModule } from '@angular/platform-browser';
2 | import { NgModule } from '@angular/core';
3 |
4 | import { AppRoutingModule } from './app-routing.module';
5 | import { AppComponent } from './app.component';
6 |
7 | import { AngularFireModule } from 'angularfire2';
8 | import { AngularFirestoreModule } from 'angularfire2/firestore';
9 | import { AngularFireAuthModule } from 'angularfire2/auth';
10 |
11 | const config = {
12 | apiKey: 'AIzaSyBogpc-AUVgVdcgoiWhE4_lKCFzfcbaSaA',
13 | authDomain: 'angularfirebase-267db.firebaseapp.com',
14 | databaseURL: 'https://angularfirebase-267db.firebaseio.com',
15 | projectId: 'angularfirebase-267db',
16 | storageBucket: 'angularfirebase-267db.appspot.com',
17 | messagingSenderId: '96751198234'
18 | };
19 |
20 | @NgModule({
21 | declarations: [AppComponent],
22 | imports: [
23 | BrowserModule,
24 | AppRoutingModule,
25 | AngularFireModule.initializeApp(config),
26 | AngularFireAuthModule,
27 | AngularFirestoreModule
28 | ],
29 | providers: [],
30 | bootstrap: [AppComponent]
31 | })
32 | export class AppModule {}
33 |
--------------------------------------------------------------------------------
/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component } from '@angular/core';
2 | import { AngularFirestore } from 'angularfire2/firestore';
3 |
4 | import { leftJoin, leftJoinDocument } from './collectionJoin';
5 | import { docJoin } from './docJoin';
6 |
7 | import { shareReplay } from 'rxjs/operators';
8 |
9 | @Component({
10 | selector: 'app-root',
11 | templateUrl: './app.component.html',
12 | styleUrls: ['./app.component.scss']
13 | })
14 | export class AppComponent {
15 | user;
16 | joined;
17 | joined2;
18 | constructor(private afs: AngularFirestore) {
19 | this.user = this.afs
20 | .doc('users/jeff')
21 | .valueChanges()
22 | .pipe(
23 | docJoin(afs, { pet: 'pets', bff: 'users', car: 'cars' }),
24 | shareReplay(1)
25 | );
26 |
27 | this.joined = this.afs
28 | .collection('users')
29 | .valueChanges()
30 | .pipe(
31 | leftJoin(afs, 'userId', 'orders', 5),
32 | shareReplay(1)
33 | );
34 |
35 | this.joined2 = this.afs
36 | .collection('users')
37 | .valueChanges()
38 | .pipe(
39 | leftJoinDocument(afs, 'pet', 'pets'),
40 | shareReplay(1)
41 | );
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, async } from '@angular/core/testing';
2 | import { RouterTestingModule } from '@angular/router/testing';
3 | import { AppComponent } from './app.component';
4 | describe('AppComponent', () => {
5 | beforeEach(async(() => {
6 | TestBed.configureTestingModule({
7 | imports: [
8 | RouterTestingModule
9 | ],
10 | declarations: [
11 | AppComponent
12 | ],
13 | }).compileComponents();
14 | }));
15 | it('should create the app', async(() => {
16 | const fixture = TestBed.createComponent(AppComponent);
17 | const app = fixture.debugElement.componentInstance;
18 | expect(app).toBeTruthy();
19 | }));
20 | it(`should have as title 'baseSimple'`, async(() => {
21 | const fixture = TestBed.createComponent(AppComponent);
22 | const app = fixture.debugElement.componentInstance;
23 | expect(app.title).toEqual('baseSimple');
24 | }));
25 | it('should render title in a h1 tag', async(() => {
26 | const fixture = TestBed.createComponent(AppComponent);
27 | fixture.detectChanges();
28 | const compiled = fixture.debugElement.nativeElement;
29 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to baseSimple!');
30 | }));
31 | });
32 |
--------------------------------------------------------------------------------
/src/app/docJoin.ts:
--------------------------------------------------------------------------------
1 | import { AngularFirestore } from 'angularfire2/firestore';
2 |
3 | import { combineLatest, defer } from 'rxjs';
4 | import { map, switchMap } from 'rxjs/operators';
5 |
6 | export const docJoin = (
7 | afs: AngularFirestore,
8 | paths: { [key: string]: string }
9 | ) => {
10 | return source =>
11 | defer(() => {
12 | let parent;
13 | const keys = Object.keys(paths);
14 |
15 | return source.pipe(
16 | switchMap(data => {
17 | // Save the parent data state
18 | parent = data;
19 |
20 | // Map each path to an Observable
21 | const docs$ = keys.map(k => {
22 | const fullPath = `${paths[k]}/${parent[k]}`;
23 | return afs.doc(fullPath).valueChanges();
24 | });
25 |
26 | // return combineLatest, it waits for all reads to finish
27 | return combineLatest(docs$);
28 | }),
29 | map(arr => {
30 | // We now have all the associated douments
31 | // Reduce them to a single object based on the parent's keys
32 | const joins = keys.reduce((acc, cur, idx) => {
33 | return { ...acc, [cur]: arr[idx] };
34 | }, {});
35 |
36 | // Return the parent doc with the joined objects
37 | return { ...parent, ...joins };
38 | })
39 | );
40 | });
41 | };
42 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "base-simple",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "test": "ng test",
9 | "lint": "ng lint",
10 | "e2e": "ng e2e"
11 | },
12 | "private": true,
13 | "dependencies": {
14 | "@angular/animations": "^6.1.0",
15 | "@angular/common": "^6.1.0",
16 | "@angular/compiler": "^6.1.0",
17 | "@angular/core": "^6.1.0",
18 | "@angular/forms": "^6.1.0",
19 | "@angular/http": "^6.1.0",
20 | "@angular/platform-browser": "^6.1.0",
21 | "@angular/platform-browser-dynamic": "^6.1.0",
22 | "@angular/router": "^6.1.0",
23 | "angularfire2": "^5.0.0-rc.12",
24 | "core-js": "^2.5.4",
25 | "firebase": "^5.4.1",
26 | "rxjs": "^6.0.0",
27 | "zone.js": "~0.8.26"
28 | },
29 | "devDependencies": {
30 | "@angular-devkit/build-angular": "~0.7.0",
31 | "@angular/cli": "~6.1.4",
32 | "@angular/compiler-cli": "^6.1.0",
33 | "@angular/language-service": "^6.1.0",
34 | "@types/jasmine": "~2.8.6",
35 | "@types/jasminewd2": "~2.0.3",
36 | "@types/node": "~8.9.4",
37 | "codelyzer": "~4.2.1",
38 | "jasmine-core": "~2.99.1",
39 | "jasmine-spec-reporter": "~4.2.1",
40 | "karma": "~1.7.1",
41 | "karma-chrome-launcher": "~2.2.0",
42 | "karma-coverage-istanbul-reporter": "~2.0.0",
43 | "karma-jasmine": "~1.1.1",
44 | "karma-jasmine-html-reporter": "^0.2.2",
45 | "protractor": "~5.4.0",
46 | "ts-node": "~5.0.1",
47 | "tslint": "~5.9.1",
48 | "typescript": "~2.7.2"
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Firestore Join Queries with Custom RxJS Operators
2 |
3 | Advanced RxJS Techniques to perform [SQL-inspired joins with Firestore](https://angularfirebase.com/lessons/firestore-joins-similar-to-sql/).
4 |
5 | ### Document Joins
6 |
7 | `docJoin` - Joins multiple docs together into a single unified object. Useful when you have multiple has-one relationships.
8 |
9 | ```
10 | +users
11 | docId=jeff {
12 | car: 'subaru'
13 | pet: 'humphrey'
14 | }
15 |
16 | +pets
17 | docId=humphrey {
18 | type: 'dog'
19 | food: 'kibble'
20 | }
21 |
22 | +cars
23 | docId=subaru {
24 | model: 'Legacy'
25 | doors: 4
26 | }
27 | ```
28 |
29 | ```ts
30 | afs.collection('users')
31 | .valueChanges()
32 | .pipe(
33 | docJoin(afs, { car: 'cars', pet: 'pets' } )
34 | )
35 |
36 |
37 | // result
38 |
39 | {
40 | ...userData
41 | pet: { type: 'dog', food: 'kibble' },
42 | car: { model: 'Legacy', doors: 4 }
43 | }
44 | ```
45 |
46 | ### Collection Joins
47 |
48 | `leftJoin` - Joins two collections by a shared document field. Useful when you have a many-to-many relationship, such as _Users have many Orders_ and _Order belongs to User_.
49 |
50 | ```
51 | +users
52 | docId=jeff {
53 | userId: 'jeff'
54 | ...data
55 | }
56 |
57 | +orders
58 | docId=a {
59 | orderNo: 'A'
60 | userId: 'jeff'
61 | }
62 |
63 | docId=b {
64 | orderNo: 'B'
65 | userId: 'jeff'
66 | }
67 | ```
68 |
69 | ```ts
70 | afs.collection('users')
71 | .valueChanges()
72 | .pipe(
73 | leftJoin(afs, 'userId', 'orders')
74 | )
75 |
76 |
77 | // result
78 |
79 | [{
80 | ...userData
81 | orders: [{ orderNo: 'A', userId: 'jeff' }, { orderNo: 'B', userId: 'jeff' }]
82 | }]
83 | ```
84 |
85 | `leftJoinDocument` - Joins a related doc to each item in a collection. Useful when the documents each have a has-one relationship to some other document. i, e. user has_one country.
86 |
87 | ```
88 | +users
89 | docId=jeff {
90 | ...data
91 | location: usa
92 | }
93 |
94 | +countries
95 | docId=usa {
96 | name: 'USA'
97 | capital: 'Washington D.C.'
98 | }
99 | ```
100 |
101 | ```ts
102 | afs.collection('users')
103 | .valueChanges()
104 | .pipe(
105 | innerJoinDocument(afs, 'location', 'countries')
106 | )
107 |
108 |
109 | // result
110 |
111 | [
112 | {
113 | ...userData
114 | location: { name: 'USA', capital: 'Washington D.C.' }
115 | },
116 | ]
117 | ```
118 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "rulesDirectory": ["node_modules/codelyzer"],
3 | "rules": {
4 | "arrow-return-shorthand": true,
5 | "callable-types": true,
6 | "class-name": true,
7 | "comment-format": [true, "check-space"],
8 | "curly": true,
9 | "deprecation": {
10 | "severity": "warn"
11 | },
12 | "eofline": true,
13 | "forin": false,
14 | "import-blacklist": [true, "rxjs/Rx"],
15 | "import-spacing": true,
16 | "indent": [true, "spaces"],
17 | "interface-over-type-literal": true,
18 | "label-position": true,
19 | "max-line-length": [true, 140],
20 | "member-access": false,
21 | "member-ordering": [
22 | true,
23 | {
24 | "order": [
25 | "static-field",
26 | "instance-field",
27 | "static-method",
28 | "instance-method"
29 | ]
30 | }
31 | ],
32 | "no-arg": true,
33 | "no-bitwise": true,
34 | "no-console": [true, "debug", "info", "time", "timeEnd", "trace"],
35 | "no-construct": true,
36 | "no-debugger": true,
37 | "no-duplicate-super": true,
38 | "no-empty": false,
39 | "no-empty-interface": true,
40 | "no-eval": true,
41 | "no-inferrable-types": [true, "ignore-params"],
42 | "no-misused-new": true,
43 | "no-non-null-assertion": true,
44 | "no-shadowed-variable": true,
45 | "no-string-literal": false,
46 | "no-string-throw": true,
47 | "no-switch-case-fall-through": true,
48 | "no-trailing-whitespace": true,
49 | "no-unnecessary-initializer": true,
50 | "no-unused-expression": true,
51 | "no-use-before-declare": true,
52 | "no-var-keyword": true,
53 | "object-literal-sort-keys": false,
54 | "one-line": [
55 | true,
56 | "check-open-brace",
57 | "check-catch",
58 | "check-else",
59 | "check-whitespace"
60 | ],
61 | "prefer-const": true,
62 | "quotemark": [true, "single"],
63 | "radix": true,
64 | "semicolon": [true, "always"],
65 | "triple-equals": [true, "allow-null-check"],
66 | "typedef-whitespace": [
67 | true,
68 | {
69 | "call-signature": "nospace",
70 | "index-signature": "nospace",
71 | "parameter": "nospace",
72 | "property-declaration": "nospace",
73 | "variable-declaration": "nospace"
74 | }
75 | ],
76 | "unified-signatures": true,
77 | "variable-name": false,
78 | "whitespace": [
79 | true,
80 | "check-branch",
81 | "check-decl",
82 | "check-operator",
83 | "check-separator",
84 | "check-type"
85 | ],
86 | "no-output-on-prefix": true,
87 | "use-input-property-decorator": true,
88 | "use-output-property-decorator": true,
89 | "use-host-property-decorator": true,
90 | "no-input-rename": true,
91 | "no-output-rename": true,
92 | "use-life-cycle-interface": true,
93 | "use-pipe-transform-interface": true,
94 | "component-class-suffix": true,
95 | "directive-class-suffix": true
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/app/collectionJoin.ts:
--------------------------------------------------------------------------------
1 | import { AngularFirestore } from 'angularfire2/firestore';
2 |
3 | import { combineLatest, pipe, of, defer } from 'rxjs';
4 | import { map, switchMap, tap } from 'rxjs/operators';
5 |
6 | export const leftJoin = (
7 | afs: AngularFirestore,
8 | field,
9 | collection,
10 | limit = 100
11 | ) => {
12 | return source =>
13 | defer(() => {
14 | // Operator state
15 | let collectionData;
16 |
17 | // Track total num of joined doc reads
18 | let totalJoins = 0;
19 |
20 | return source.pipe(
21 | switchMap(data => {
22 | // Clear mapping on each emitted val ;
23 |
24 | // Save the parent data state
25 | collectionData = data as any[];
26 |
27 | const reads$ = [];
28 | for (const doc of collectionData) {
29 | // Push doc read to Array
30 |
31 | if (doc[field]) {
32 | // Perform query on join key, with optional limit
33 | const q = ref => ref.where(field, '==', doc[field]).limit(limit);
34 |
35 | reads$.push(afs.collection(collection, q).valueChanges());
36 | } else {
37 | reads$.push(of([]));
38 | }
39 | }
40 |
41 | return combineLatest(reads$);
42 | }),
43 | map(joins => {
44 | return collectionData.map((v, i) => {
45 | totalJoins += joins[i].length;
46 | return { ...v, [collection]: joins[i] || null };
47 | });
48 | }),
49 | tap(final => {
50 | console.log(
51 | `Queried ${(final as any).length}, Joined ${totalJoins} docs`
52 | );
53 | totalJoins = 0;
54 | })
55 | );
56 | });
57 | };
58 |
59 | export const leftJoinDocument = (afs: AngularFirestore, field, collection) => {
60 | return source =>
61 | defer(() => {
62 | // Operator state
63 | let collectionData;
64 | const cache = new Map();
65 |
66 | return source.pipe(
67 | switchMap(data => {
68 | // Clear mapping on each emitted val ;
69 | cache.clear();
70 |
71 | // Save the parent data state
72 | collectionData = data as any[];
73 |
74 | const reads$ = [];
75 | let i = 0;
76 | for (const doc of collectionData) {
77 | // Skip if doc field does not exist or is already in cache
78 | if (!doc[field] || cache.get(doc[field])) {
79 | continue;
80 | }
81 |
82 | // Push doc read to Array
83 | reads$.push(
84 | afs
85 | .collection(collection)
86 | .doc(doc[field])
87 | .valueChanges()
88 | );
89 | cache.set(doc[field], i);
90 | i++;
91 | }
92 |
93 | return reads$.length ? combineLatest(reads$) : of([]);
94 | }),
95 | map(joins => {
96 | return collectionData.map((v, i) => {
97 | const joinIdx = cache.get(v[field]);
98 | return { ...v, [field]: joins[joinIdx] || null };
99 | });
100 | }),
101 | tap(final =>
102 | console.log(
103 | `Queried ${(final as any).length}, Joined ${cache.size} docs`
104 | )
105 | )
106 | );
107 | });
108 | };
109 |
--------------------------------------------------------------------------------
/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/
22 | // import 'core-js/es6/symbol';
23 | // import 'core-js/es6/object';
24 | // import 'core-js/es6/function';
25 | // import 'core-js/es6/parse-int';
26 | // import 'core-js/es6/parse-float';
27 | // import 'core-js/es6/number';
28 | // import 'core-js/es6/math';
29 | // import 'core-js/es6/string';
30 | // import 'core-js/es6/date';
31 | // import 'core-js/es6/array';
32 | // import 'core-js/es6/regexp';
33 | // import 'core-js/es6/map';
34 | // import 'core-js/es6/weak-map';
35 | // import 'core-js/es6/set';
36 |
37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
38 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
39 |
40 | /** IE10 and IE11 requires the following for the Reflect API. */
41 | // import 'core-js/es6/reflect';
42 |
43 |
44 | /** Evergreen browsers require these. **/
45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
46 | import 'core-js/es7/reflect';
47 |
48 |
49 | /**
50 | * Web Animations `@angular/platform-browser/animations`
51 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
52 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
53 | **/
54 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
55 |
56 | /**
57 | * By default, zone.js will patch all possible macroTask and DomEvents
58 | * user can disable parts of macroTask/DomEvents patch by setting following flags
59 | */
60 |
61 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
62 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
63 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
64 |
65 | /*
66 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
67 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
68 | */
69 | // (window as any).__Zone_enable_cross_context_check = true;
70 |
71 | /***************************************************************************************************
72 | * Zone JS is required by default for Angular itself.
73 | */
74 | import 'zone.js/dist/zone'; // Included with Angular CLI.
75 |
76 |
77 |
78 | /***************************************************************************************************
79 | * APPLICATION IMPORTS
80 | */
81 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "baseSimple": {
7 | "root": "",
8 | "sourceRoot": "src",
9 | "projectType": "application",
10 | "prefix": "app",
11 | "schematics": {
12 | "@schematics/angular:component": {
13 | "styleext": "scss"
14 | }
15 | },
16 | "architect": {
17 | "build": {
18 | "builder": "@angular-devkit/build-angular:browser",
19 | "options": {
20 | "outputPath": "dist/baseSimple",
21 | "index": "src/index.html",
22 | "main": "src/main.ts",
23 | "polyfills": "src/polyfills.ts",
24 | "tsConfig": "src/tsconfig.app.json",
25 | "assets": [
26 | "src/favicon.ico",
27 | "src/assets"
28 | ],
29 | "styles": [
30 | "src/styles.scss"
31 | ],
32 | "scripts": []
33 | },
34 | "configurations": {
35 | "production": {
36 | "fileReplacements": [
37 | {
38 | "replace": "src/environments/environment.ts",
39 | "with": "src/environments/environment.prod.ts"
40 | }
41 | ],
42 | "optimization": true,
43 | "outputHashing": "all",
44 | "sourceMap": false,
45 | "extractCss": true,
46 | "namedChunks": false,
47 | "aot": true,
48 | "extractLicenses": true,
49 | "vendorChunk": false,
50 | "buildOptimizer": true
51 | }
52 | }
53 | },
54 | "serve": {
55 | "builder": "@angular-devkit/build-angular:dev-server",
56 | "options": {
57 | "browserTarget": "baseSimple:build"
58 | },
59 | "configurations": {
60 | "production": {
61 | "browserTarget": "baseSimple:build:production"
62 | }
63 | }
64 | },
65 | "extract-i18n": {
66 | "builder": "@angular-devkit/build-angular:extract-i18n",
67 | "options": {
68 | "browserTarget": "baseSimple:build"
69 | }
70 | },
71 | "test": {
72 | "builder": "@angular-devkit/build-angular:karma",
73 | "options": {
74 | "main": "src/test.ts",
75 | "polyfills": "src/polyfills.ts",
76 | "tsConfig": "src/tsconfig.spec.json",
77 | "karmaConfig": "src/karma.conf.js",
78 | "styles": [
79 | "src/styles.scss"
80 | ],
81 | "scripts": [],
82 | "assets": [
83 | "src/favicon.ico",
84 | "src/assets"
85 | ]
86 | }
87 | },
88 | "lint": {
89 | "builder": "@angular-devkit/build-angular:tslint",
90 | "options": {
91 | "tsConfig": [
92 | "src/tsconfig.app.json",
93 | "src/tsconfig.spec.json"
94 | ],
95 | "exclude": [
96 | "**/node_modules/**"
97 | ]
98 | }
99 | }
100 | }
101 | },
102 | "baseSimple-e2e": {
103 | "root": "e2e/",
104 | "projectType": "application",
105 | "architect": {
106 | "e2e": {
107 | "builder": "@angular-devkit/build-angular:protractor",
108 | "options": {
109 | "protractorConfig": "e2e/protractor.conf.js",
110 | "devServerTarget": "baseSimple:serve"
111 | },
112 | "configurations": {
113 | "production": {
114 | "devServerTarget": "baseSimple:serve:production"
115 | }
116 | }
117 | },
118 | "lint": {
119 | "builder": "@angular-devkit/build-angular:tslint",
120 | "options": {
121 | "tsConfig": "e2e/tsconfig.e2e.json",
122 | "exclude": [
123 | "**/node_modules/**"
124 | ]
125 | }
126 | }
127 | }
128 | }
129 | },
130 | "defaultProject": "baseSimple"
131 | }
--------------------------------------------------------------------------------