Skip to content
This repository has been archived by the owner on Apr 4, 2023. It is now read-only.

Commit

Permalink
#548 Compatibility with the Firebase Web API
Browse files Browse the repository at this point in the history
  • Loading branch information
EddyVerbruggen committed Nov 21, 2017
1 parent 7a9cc9f commit 48c609d
Show file tree
Hide file tree
Showing 9 changed files with 2,337 additions and 82 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
*.js.map
build/
*.log.*
src/*.d.ts
src/**/*.d.ts
!src/firebase.d.ts
!src/index.d.ts
!src/references.d.ts
!src/platforms/web/typings/firebase-webapi.d.ts
!src/scripts/*.js
!demo/karma.conf.js
!demo/app/tests/*.js
Expand Down
225 changes: 150 additions & 75 deletions demo/app/main-page.xml

Large diffs are not rendered by default.

236 changes: 235 additions & 1 deletion demo/app/main-view-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import { Observable } from "tns-core-modules/data/observable";
import { alert, prompt } from "tns-core-modules/ui/dialogs";
import { ios as iosUtils } from "tns-core-modules/utils/utils";
import { isIOS } from "tns-core-modules/platform";
import { AddEventListenerResult } from "nativescript-plugin-firebase";
import { AddEventListenerResult, User } from "nativescript-plugin-firebase";
import * as fs from "tns-core-modules/file-system";

const firebase = require("nativescript-plugin-firebase");
const firebaseWebApi = require("nativescript-plugin-firebase/app");

declare const assert: any;

Expand All @@ -13,6 +15,223 @@ export class HelloWorldModel extends Observable {
public userEmailOrPhone: string;
private userListenerWrapper: AddEventListenerResult;
private companiesListenerWrapper: AddEventListenerResult;
private onAuthStateChangedHandlerSet = false;


/***********************************************
* Web API usage examples
***********************************************/

private ensureWebOnAuthChangedHandler(): void {
if (!this.onAuthStateChangedHandlerSet) {
this.onAuthStateChangedHandlerSet = true;
firebaseWebApi.auth().onAuthStateChanged((user?: User) => {
console.log(">> auth state changed: " + user);
if (user) {
this.set("userEmailOrPhone", user.email ? user.email : (user.phoneNumber ? user.phoneNumber : "N/A"));
alert({
title: "User signed in",
message: JSON.stringify(user),
okButtonText: "Nice!"
});
} else {
alert({
title: "User signed out",
okButtonText: "Bye!"
});
}
});
}
}

public doWebInit(): void {
firebaseWebApi.initializeApp();
}

public doWebLoginAnonymously(): void {
this.ensureWebOnAuthChangedHandler();
firebaseWebApi.auth().signInAnonymously()
.catch(err => {
alert({
title: "Login error",
message: JSON.stringify(err),
okButtonText: "OK, pity"
});
}
);
}

public doWebLoginByPassword(): void {
this.ensureWebOnAuthChangedHandler();
firebaseWebApi.auth().signInWithEmailAndPassword('[email protected]', 'firebase')
.catch(err => {
alert({
title: "Login error",
message: JSON.stringify(err),
okButtonText: "OK, pity"
});
}
);
}

public doWebFetchProvidersForEmail(): void {
const user = firebaseWebApi.auth().currentUser;
if (!user || !user.email) {
alert({
title: "Can't fetch providers",
message: "No user with emailaddress logged in.",
okButtonText: "OK, makes sense.."
});
return;
}

firebaseWebApi.auth().fetchProvidersForEmail(user.email).then(
result => {
alert({
title: `Providers for ${user.email}`,
message: JSON.stringify(result), // likely to be ["password"]
okButtonText: "Thanks!"
});
},
errorMessage => {
alert({
title: "Fetch Providers for Email error",
message: errorMessage,
okButtonText: "OK, pity.."
});
}
);
}

public doWebLogout(): void {
firebaseWebApi.auth().signOut()
.then(() => {
this.set("userEmailOrPhone", null);
alert({
title: "Logout OK",
okButtonText: "OK, bye!"
});
})
.catch(error => {
alert({
title: "Logout error",
message: JSON.stringify(error),
okButtonText: "Hmmkay"
});
}
);
}

public doWebCreateUser(): void {
firebaseWebApi.auth().createUserWithEmailAndPassword('[email protected]', 'firebase')
.then(result => {
alert({
title: "User created",
message: JSON.stringify(result),
okButtonText: "Nice!"
});
})
.catch(
error => {
alert({
title: "No user created",
message: JSON.stringify(error),
okButtonText: "OK, got it"
});
}
);
}

public doWebGetCurrentUser(): void {
const user = firebaseWebApi.auth().currentUser;
if (user) {
alert({
title: "Current user",
message: JSON.stringify(user),
okButtonText: "Nice!"
});
} else {
alert({
title: "No current user",
okButtonText: "OK, thanks"
});
}
}

public doWebAddValueEventListenerForCompanies(): void {
const path = "/companies";
const onValueEvent = result => {
if (result.error) {
alert({
title: "Listener error",
message: result.error,
okButtonText: "Darn!"
});
} else {
this.set("path", path);
this.set("key", result.key);
this.set("value", JSON.stringify(result.val()));
}
};

firebaseWebApi.database().ref(path).on("value", onValueEvent);
}

public doWebRemoveValueEventListenersForCompanies(): void {
const path = "/companies";
firebaseWebApi.database().ref(path).off("value");
}

public doWebGetValueForCompanies(): void {
const path = "/companies";
firebaseWebApi.database().ref(path)
.once("value")
.then(result => {
this.set("path", path);
this.set("key", result.key);
this.set("value", JSON.stringify(result.val()));
})
.catch(error => console.log("doWebGetValueForCompanies error: " + error));
}

public doWebStoreCompaniesBySetValue(): void {
firebaseWebApi.database().ref("/companies")
.set([
{
name: 'Telerik (web)',
country: 'Bulgaria',
since: 2000,
updateTs: firebase.ServerValue.TIMESTAMP
},
{
name: 'Google (web)',
country: 'USA',
since: 1900,
updateTs: firebase.ServerValue.TIMESTAMP
}
]
)
.then(() => console.log("firebase.setValue done"))
.catch(error => console.log("firebase.setValue error: " + error));
}

public doWebRemoveCompanies(): void {
firebaseWebApi.database().ref("/companies").remove()
.then(() => console.log("firebase.remove done"))
.catch((err) => console.log("firebase.remove error: " + err));
}

public doWebQueryBulgarianCompanies(): void {
const path = "/companies";
const child = "name";
firebaseWebApi.database().ref(path).orderByChild(child);
}



/***********************************************
* Native API usage examples
***********************************************/

public doInit(): void {
firebase.init({
Expand Down Expand Up @@ -724,6 +943,21 @@ export class HelloWorldModel extends Observable {
);
}

public doGetValueForCompanies(): void {
firebase.getValue('/companies').then(
result => {
alert({
title: "Value retrieved",
message: JSON.stringify(result),
okButtonText: "OK"
});
},
error => {
console.log("doGetValueForCompanies error: " + error);
}
);
}

public doUserStoreByPush(): void {
firebase.push(
'/users',
Expand Down
2 changes: 1 addition & 1 deletion demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
}
},
"dependencies": {
"nativescript-plugin-firebase": "../src",
"nativescript-plugin-firebase": "file:../src",
"nativescript-theme-core": "^1.0.4",
"nativescript-unit-test-runner": "^0.3.4",
"tns-core-modules": "^3.3.0"
Expand Down
80 changes: 80 additions & 0 deletions src/app/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import * as firebase from "../../firebase";
import { LoginType, User } from "../../firebase";

export module auth {
export class Auth {
private authStateChangedHandler;
public currentUser: User;

public onAuthStateChanged(handler: (user: User) => void): void {
this.authStateChangedHandler = handler;
console.log(">> added onAuthStateChanged handler");
};

public signOut(): Promise<any> {
return new Promise((resolve, reject) => {
firebase.logout()
.then(() => {
this.currentUser = undefined;
this.authStateChangedHandler && this.authStateChangedHandler();
resolve();
})
.catch(err => {
reject({
// code: "",
message: err
});
});
});
}

public signInWithEmailAndPassword(email: string, password: string): Promise<any> {
return new Promise((resolve, reject) => {
firebase.login({
type: LoginType.PASSWORD,
passwordOptions: {
email: email,
password: password
}
}).then((user: User) => {
this.currentUser = user;
this.authStateChangedHandler && this.authStateChangedHandler(user);
resolve();
}, (err => {
reject({
// code: "",
message: err
});
}));
});
}

public createUserWithEmailAndPassword(email: string, password: string): Promise<any> {
return firebase.createUser({
email: email,
password: password
});
}

public signInAnonymously(): Promise<any> {
return new Promise((resolve, reject) => {
firebase.login({
type: LoginType.ANONYMOUS
}).then((user: User) => {
this.currentUser = user;
this.authStateChangedHandler && this.authStateChangedHandler(user);
resolve();
}, (err => {
reject({
// code: "",
message: err
});
}));
});
}

public fetchProvidersForEmail(email: string): Promise<any> {
return firebase.fetchProvidersForEmail(email);
}
}
}
Loading

0 comments on commit 48c609d

Please sign in to comment.