Skip to content

runOutsideAngular for Universal compatibility and allow advanced configuration with DI #1454

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Mar 20, 2018
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 3 additions & 18 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,9 @@
import { NgModule, NgZone } from '@angular/core';
import { FirebaseApp, AngularFireModule } from 'angularfire2';
import { NgModule } from '@angular/core';
import { AngularFireAuth } from './auth';
import '@firebase/auth';

export function _getAngularFireAuth(app: FirebaseApp) {
return new AngularFireAuth(app);
}

export const AngularFireAuthProvider = {
provide: AngularFireAuth,
useFactory: _getAngularFireAuth,
deps: [ FirebaseApp ]
};

export const AUTH_PROVIDERS = [
AngularFireAuthProvider,
];
import { FirebaseApp } from '@firebase/app-types'

@NgModule({
imports: [ AngularFireModule ],
providers: [ AUTH_PROVIDERS ]
providers: [ AngularFireAuth ]
})
export class AngularFireAuthModule { }
47 changes: 43 additions & 4 deletions src/auth/auth.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FirebaseApp as FBApp } from '@firebase/app-types';
import { FirebaseApp } from '@firebase/app-types';
import { User } from '@firebase/auth-types';
import { ReflectiveInjector, Provider } from '@angular/core';
import { Observable } from 'rxjs/Observable'
Expand All @@ -8,7 +8,7 @@ import { TestBed, inject } from '@angular/core/testing';
import { _do } from 'rxjs/operator/do';
import { take } from 'rxjs/operator/take';
import { skip } from 'rxjs/operator/skip';
import { FirebaseApp, FirebaseAppConfig, AngularFireModule } from 'angularfire2';
import { FirebaseAppConfig, AngularFireModule, FirebaseAppName } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import { COMMON_CONFIG } from './test-config';

Expand All @@ -26,7 +26,7 @@ const firebaseUser = <User> {
};

describe('AngularFireAuth', () => {
let app: FBApp;
let app: FirebaseApp;
let afAuth: AngularFireAuth;
let authSpy: jasmine.Spy;
let mockAuthState: Subject<User>;
Expand All @@ -51,7 +51,7 @@ describe('AngularFireAuth', () => {
});

afterEach(done => {
app.delete().then(done, done.fail);
afAuth.auth.app.delete().then(done, done.fail);
});

describe('Zones', () => {
Expand Down Expand Up @@ -123,3 +123,42 @@ describe('AngularFireAuth', () => {

});

const FIREBASE_APP_NAME_TOO = (Math.random() + 1).toString(36).substring(7);

describe('AngularFireAuth with different app', () => {
let app: FirebaseApp;
let afAuth: AngularFireAuth;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AngularFireModule.initializeApp(COMMON_CONFIG),
AngularFireAuthModule
],
providers: [
{ provide: FirebaseAppName, useValue: FIREBASE_APP_NAME_TOO },
{ provide: FirebaseAppConfig, useValue: COMMON_CONFIG }
]
});
inject([FirebaseApp, AngularFireAuth], (app_: FirebaseApp, _afAuth: AngularFireAuth) => {
app = app_;
afAuth = _afAuth;
})();
});

afterEach(done => {
app.delete().then(done, done.fail);
});

describe('<constructor>', () => {

it('should be an AngularFireAuth type', () => {
expect(afAuth instanceof AngularFireAuth).toEqual(true);
});

it('should have an initialized Firebase app instance member', () => {
expect(afAuth.auth.app.name).toEqual(FIREBASE_APP_NAME_TOO);
});
});

});
42 changes: 27 additions & 15 deletions src/auth/auth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { FirebaseAuth, User } from '@firebase/auth-types';
import { Injectable, NgZone } from '@angular/core';
import { FirebaseOptions } from '@firebase/app-types';
import { Injectable, Inject, Optional, NgZone } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { observeOn } from 'rxjs/operator/observeOn';
import { FirebaseApp, ZoneScheduler } from 'angularfire2';

import { FirebaseAppConfig, FirebaseAppName, firebaseAppFactory, FirebaseZoneScheduler } from 'angularfire2';

import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/of';
Expand All @@ -26,22 +28,32 @@ export class AngularFireAuth {
*/
public readonly idToken: Observable<string|null>;

constructor(public app: FirebaseApp) {
this.auth = app.auth();

const authState$ = new Observable(subscriber => {
const unsubscribe = this.auth.onAuthStateChanged(subscriber);
return { unsubscribe };
constructor(
@Inject(FirebaseAppConfig) config:FirebaseOptions,
@Optional() @Inject(FirebaseAppName) name:string
) {
const app = firebaseAppFactory(config, name);
this.auth = app.auth!();

const authStateZone = new NgZone({});
this.authState = authStateZone.runOutsideAngular(() => {
const authState$ = new Observable(subscriber => {
const unsubscribe = this.auth.onAuthStateChanged(subscriber);
return { unsubscribe };
});
return observeOn.call(authState$, new FirebaseZoneScheduler(authStateZone));
});
this.authState = observeOn.call(authState$, new ZoneScheduler(Zone.current));

const idToken$ = new Observable<User|null>(subscriber => {
const unsubscribe = this.auth.onIdTokenChanged(subscriber);
return { unsubscribe };
}).switchMap(user => {
return user ? Observable.fromPromise(user.getIdToken()) : Observable.of(null)
const idTokenZone = new NgZone({});
this.idToken = idTokenZone.runOutsideAngular(() => {
const idToken$ = new Observable(subscriber => {
const unsubscribe = this.auth.onIdTokenChanged(subscriber);
return { unsubscribe };
}).switchMap((user:User|null) => {
return user ? Observable.fromPromise(user.getIdToken()) : Observable.of(null)
});
return observeOn.call(idToken$, new FirebaseZoneScheduler(idTokenZone));
});
this.idToken = observeOn.call(idToken$, new ZoneScheduler(Zone.current));
}

}
5 changes: 3 additions & 2 deletions src/core/angularfire2.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

import { Reference } from '@firebase/database-types';
import { FirebaseApp } from '@firebase/app-types';
import { TestBed, inject, withModule, async } from '@angular/core/testing';
import { ReflectiveInjector, Provider, PlatformRef, NgModule, Compiler, ApplicationRef, CompilerFactory } from '@angular/core';
import { FirebaseApp, FirebaseAppConfig, AngularFireModule } from 'angularfire2';
import { FirebaseAppConfig, AngularFireModule } from 'angularfire2';
import { Subscription } from 'rxjs/Subscription';
import { COMMON_CONFIG } from './test-config';
import { BrowserModule } from '@angular/platform-browser';
Expand All @@ -25,7 +26,7 @@ describe('angularfire', () => {

inject([FirebaseApp, PlatformRef], (_app: FirebaseApp, _platform: PlatformRef) => {
app = _app;
rootRef = app.database().ref();
rootRef = app.database!().ref();
questionsRef = rootRef.child('questions');
listOfQuestionsRef = rootRef.child('list-of-questions');
defaultPlatform = _platform;
Expand Down
76 changes: 35 additions & 41 deletions src/core/angularfire2.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,47 @@
import { FirebaseAppConfigToken, FirebaseApp, _firebaseAppFactory } from './firebase.app.module';
import { Injectable, InjectionToken, NgModule } from '@angular/core';
import { InjectionToken, NgZone, NgModule } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Scheduler } from 'rxjs/Scheduler';
import { queue } from 'rxjs/scheduler/queue';

export interface FirebaseAppConfig {
apiKey?: string;
authDomain?: string;
databaseURL?: string;
storageBucket?: string;
messagingSenderId?: string;
projectId?: string;
import firebase from '@firebase/app';
import { FirebaseApp, FirebaseOptions } from '@firebase/app-types';

export function firebaseAppFactory(config: FirebaseOptions, name?: string): FirebaseApp {
const appName = name || '[DEFAULT]';
const existingApp = firebase.apps.filter(app => app.name == appName)[0];
return existingApp || firebase.initializeApp(config, appName);
}

const FirebaseAppName = new InjectionToken<string>('FirebaseAppName');
export const FirebaseAppName = new InjectionToken<string>('angularfire2.appName');
export const FirebaseAppConfig = new InjectionToken<FirebaseOptions>('angularfire2.config');

export const FirebaseAppProvider = {
provide: FirebaseApp,
useFactory: _firebaseAppFactory,
deps: [ FirebaseAppConfigToken, FirebaseAppName ]
};
// Put in database.ts when we dropped depreciated
export const RealtimeDatabaseURL = new InjectionToken<string>('angularfire2.realtimeDatabaseURL');

@NgModule({
providers: [ FirebaseAppProvider ],
})
export class AngularFireModule {
static initializeApp(config: FirebaseAppConfig, appName?: string) {
return {
ngModule: AngularFireModule,
providers: [
{ provide: FirebaseAppConfigToken, useValue: config },
{ provide: FirebaseAppName, useValue: appName }
]
}
}
export const FirebaseAppProvider = {
provide: FirebaseApp,
useFactory: firebaseAppFactory,
deps: [ FirebaseAppConfig, FirebaseAppName ]
};

@NgModule({
providers: [ FirebaseAppProvider ],
})
export class AngularFireModule {
static initializeApp(config: FirebaseOptions, appName?: string) {
return {
ngModule: AngularFireModule,
providers: [
{ provide: FirebaseAppConfig, useValue: config },
{ provide: FirebaseAppName, useValue: appName }
]
}
}
}

/**
* TODO: remove this scheduler once Rx has a more robust story for working
* with zones.
*/
export class ZoneScheduler {

// TODO: Correctly add ambient zone typings instead of using any.
constructor(public zone: any) {}

export class FirebaseZoneScheduler {
constructor(public zone: NgZone) {}
schedule(...args: any[]): Subscription {
return <Subscription>this.zone.run(() => queue.schedule.apply(queue, args));
return <Subscription>this.zone.runGuarded(function() { return queue.schedule.apply(queue, args)});
}
}

export { FirebaseApp, FirebaseAppName, FirebaseAppConfigToken };
}
40 changes: 0 additions & 40 deletions src/core/firebase.app.module.ts

This file was deleted.

19 changes: 2 additions & 17 deletions src/database-deprecated/database.module.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,9 @@
import { NgModule } from '@angular/core';
import { AngularFireModule, FirebaseApp } from 'angularfire2';
import { FirebaseApp } from '@firebase/app-types';
import { AngularFireDatabase } from './database';
import '@firebase/database';

export function _getAngularFireDatabase(app: FirebaseApp) {
return new AngularFireDatabase(app);
}

export const AngularFireDatabaseProvider = {
provide: AngularFireDatabase,
useFactory: _getAngularFireDatabase,
deps: [ FirebaseApp ]
};

export const DATABASE_PROVIDERS = [
AngularFireDatabaseProvider,
];

@NgModule({
imports: [ AngularFireModule ],
providers: [ DATABASE_PROVIDERS ]
providers: [ AngularFireDatabase ]
})
export class AngularFireDatabaseModule { }
19 changes: 13 additions & 6 deletions src/database-deprecated/database.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { FirebaseDatabase } from '@firebase/database-types';
import { Inject, Injectable } from '@angular/core';
import { FirebaseAppConfigToken, FirebaseAppConfig, FirebaseApp } from 'angularfire2';
import { Inject, Injectable, Optional } from '@angular/core';
import { FirebaseApp } from '@firebase/app-types';
import { FirebaseListFactory } from './firebase_list_factory';
import { FirebaseListObservable } from './firebase_list_observable';
import { FirebaseListFactoryOpts, FirebaseObjectFactoryOpts, PathReference } from './interfaces';
import { FirebaseObjectFactory } from './firebase_object_factory';
import { FirebaseObjectObservable } from './firebase_object_observable';
import * as utils from './utils';
import { FirebaseOptions } from '@firebase/app-types';
import { FirebaseAppConfig, FirebaseAppName, RealtimeDatabaseURL, firebaseAppFactory } from 'angularfire2';

@Injectable()
export class AngularFireDatabase {
Expand All @@ -16,17 +18,22 @@ export class AngularFireDatabase {
*/
database: FirebaseDatabase;

constructor(public app: FirebaseApp) {
this.database = app.database();
constructor(
@Inject(FirebaseAppConfig) config:FirebaseOptions,
@Optional() @Inject(FirebaseAppName) name:string,
@Optional() @Inject(RealtimeDatabaseURL) databaseURL:string
) {
const app = firebaseAppFactory(config, name);
this.database = app.database!(databaseURL);
}

list(pathOrRef: PathReference, opts?:FirebaseListFactoryOpts):FirebaseListObservable<any[]> {
const ref = utils.getRef(this.app, pathOrRef);
const ref = utils.getRef(this.database, pathOrRef);
return FirebaseListFactory(ref, opts);
}

object(pathOrRef: PathReference, opts?:FirebaseObjectFactoryOpts):FirebaseObjectObservable<any> {
const ref = utils.getRef(this.app, pathOrRef);
const ref = utils.getRef(this.database, pathOrRef);
return FirebaseObjectFactory(ref, opts);
}

Expand Down
Loading