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

Commit 48c609d

Browse files
#548 Compatibility with the Firebase Web API
1 parent 7a9cc9f commit 48c609d

File tree

9 files changed

+2337
-82
lines changed

9 files changed

+2337
-82
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
*.js.map
77
build/
88
*.log.*
9-
src/*.d.ts
9+
src/**/*.d.ts
1010
!src/firebase.d.ts
1111
!src/index.d.ts
1212
!src/references.d.ts
13+
!src/platforms/web/typings/firebase-webapi.d.ts
1314
!src/scripts/*.js
1415
!demo/karma.conf.js
1516
!demo/app/tests/*.js

demo/app/main-page.xml

Lines changed: 150 additions & 75 deletions
Large diffs are not rendered by default.

demo/app/main-view-model.ts

Lines changed: 235 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import { Observable } from "tns-core-modules/data/observable";
22
import { alert, prompt } from "tns-core-modules/ui/dialogs";
33
import { ios as iosUtils } from "tns-core-modules/utils/utils";
44
import { isIOS } from "tns-core-modules/platform";
5-
import { AddEventListenerResult } from "nativescript-plugin-firebase";
5+
import { AddEventListenerResult, User } from "nativescript-plugin-firebase";
66
import * as fs from "tns-core-modules/file-system";
7+
78
const firebase = require("nativescript-plugin-firebase");
9+
const firebaseWebApi = require("nativescript-plugin-firebase/app");
810

911
declare const assert: any;
1012

@@ -13,6 +15,223 @@ export class HelloWorldModel extends Observable {
1315
public userEmailOrPhone: string;
1416
private userListenerWrapper: AddEventListenerResult;
1517
private companiesListenerWrapper: AddEventListenerResult;
18+
private onAuthStateChangedHandlerSet = false;
19+
20+
21+
/***********************************************
22+
* Web API usage examples
23+
***********************************************/
24+
25+
private ensureWebOnAuthChangedHandler(): void {
26+
if (!this.onAuthStateChangedHandlerSet) {
27+
this.onAuthStateChangedHandlerSet = true;
28+
firebaseWebApi.auth().onAuthStateChanged((user?: User) => {
29+
console.log(">> auth state changed: " + user);
30+
if (user) {
31+
this.set("userEmailOrPhone", user.email ? user.email : (user.phoneNumber ? user.phoneNumber : "N/A"));
32+
alert({
33+
title: "User signed in",
34+
message: JSON.stringify(user),
35+
okButtonText: "Nice!"
36+
});
37+
} else {
38+
alert({
39+
title: "User signed out",
40+
okButtonText: "Bye!"
41+
});
42+
}
43+
});
44+
}
45+
}
46+
47+
public doWebInit(): void {
48+
firebaseWebApi.initializeApp();
49+
}
50+
51+
public doWebLoginAnonymously(): void {
52+
this.ensureWebOnAuthChangedHandler();
53+
firebaseWebApi.auth().signInAnonymously()
54+
.catch(err => {
55+
alert({
56+
title: "Login error",
57+
message: JSON.stringify(err),
58+
okButtonText: "OK, pity"
59+
});
60+
}
61+
);
62+
}
63+
64+
public doWebLoginByPassword(): void {
65+
this.ensureWebOnAuthChangedHandler();
66+
firebaseWebApi.auth().signInWithEmailAndPassword('[email protected]', 'firebase')
67+
.catch(err => {
68+
alert({
69+
title: "Login error",
70+
message: JSON.stringify(err),
71+
okButtonText: "OK, pity"
72+
});
73+
}
74+
);
75+
}
76+
77+
public doWebFetchProvidersForEmail(): void {
78+
const user = firebaseWebApi.auth().currentUser;
79+
if (!user || !user.email) {
80+
alert({
81+
title: "Can't fetch providers",
82+
message: "No user with emailaddress logged in.",
83+
okButtonText: "OK, makes sense.."
84+
});
85+
return;
86+
}
87+
88+
firebaseWebApi.auth().fetchProvidersForEmail(user.email).then(
89+
result => {
90+
alert({
91+
title: `Providers for ${user.email}`,
92+
message: JSON.stringify(result), // likely to be ["password"]
93+
okButtonText: "Thanks!"
94+
});
95+
},
96+
errorMessage => {
97+
alert({
98+
title: "Fetch Providers for Email error",
99+
message: errorMessage,
100+
okButtonText: "OK, pity.."
101+
});
102+
}
103+
);
104+
}
105+
106+
public doWebLogout(): void {
107+
firebaseWebApi.auth().signOut()
108+
.then(() => {
109+
this.set("userEmailOrPhone", null);
110+
alert({
111+
title: "Logout OK",
112+
okButtonText: "OK, bye!"
113+
});
114+
})
115+
.catch(error => {
116+
alert({
117+
title: "Logout error",
118+
message: JSON.stringify(error),
119+
okButtonText: "Hmmkay"
120+
});
121+
}
122+
);
123+
}
124+
125+
public doWebCreateUser(): void {
126+
firebaseWebApi.auth().createUserWithEmailAndPassword('[email protected]', 'firebase')
127+
.then(result => {
128+
alert({
129+
title: "User created",
130+
message: JSON.stringify(result),
131+
okButtonText: "Nice!"
132+
});
133+
})
134+
.catch(
135+
error => {
136+
alert({
137+
title: "No user created",
138+
message: JSON.stringify(error),
139+
okButtonText: "OK, got it"
140+
});
141+
}
142+
);
143+
}
144+
145+
public doWebGetCurrentUser(): void {
146+
const user = firebaseWebApi.auth().currentUser;
147+
if (user) {
148+
alert({
149+
title: "Current user",
150+
message: JSON.stringify(user),
151+
okButtonText: "Nice!"
152+
});
153+
} else {
154+
alert({
155+
title: "No current user",
156+
okButtonText: "OK, thanks"
157+
});
158+
}
159+
}
160+
161+
public doWebAddValueEventListenerForCompanies(): void {
162+
const path = "/companies";
163+
const onValueEvent = result => {
164+
if (result.error) {
165+
alert({
166+
title: "Listener error",
167+
message: result.error,
168+
okButtonText: "Darn!"
169+
});
170+
} else {
171+
this.set("path", path);
172+
this.set("key", result.key);
173+
this.set("value", JSON.stringify(result.val()));
174+
}
175+
};
176+
177+
firebaseWebApi.database().ref(path).on("value", onValueEvent);
178+
}
179+
180+
public doWebRemoveValueEventListenersForCompanies(): void {
181+
const path = "/companies";
182+
firebaseWebApi.database().ref(path).off("value");
183+
}
184+
185+
public doWebGetValueForCompanies(): void {
186+
const path = "/companies";
187+
firebaseWebApi.database().ref(path)
188+
.once("value")
189+
.then(result => {
190+
this.set("path", path);
191+
this.set("key", result.key);
192+
this.set("value", JSON.stringify(result.val()));
193+
})
194+
.catch(error => console.log("doWebGetValueForCompanies error: " + error));
195+
}
196+
197+
public doWebStoreCompaniesBySetValue(): void {
198+
firebaseWebApi.database().ref("/companies")
199+
.set([
200+
{
201+
name: 'Telerik (web)',
202+
country: 'Bulgaria',
203+
since: 2000,
204+
updateTs: firebase.ServerValue.TIMESTAMP
205+
},
206+
{
207+
name: 'Google (web)',
208+
country: 'USA',
209+
since: 1900,
210+
updateTs: firebase.ServerValue.TIMESTAMP
211+
}
212+
]
213+
)
214+
.then(() => console.log("firebase.setValue done"))
215+
.catch(error => console.log("firebase.setValue error: " + error));
216+
}
217+
218+
public doWebRemoveCompanies(): void {
219+
firebaseWebApi.database().ref("/companies").remove()
220+
.then(() => console.log("firebase.remove done"))
221+
.catch((err) => console.log("firebase.remove error: " + err));
222+
}
223+
224+
public doWebQueryBulgarianCompanies(): void {
225+
const path = "/companies";
226+
const child = "name";
227+
firebaseWebApi.database().ref(path).orderByChild(child);
228+
}
229+
230+
231+
232+
/***********************************************
233+
* Native API usage examples
234+
***********************************************/
16235

17236
public doInit(): void {
18237
firebase.init({
@@ -724,6 +943,21 @@ export class HelloWorldModel extends Observable {
724943
);
725944
}
726945

946+
public doGetValueForCompanies(): void {
947+
firebase.getValue('/companies').then(
948+
result => {
949+
alert({
950+
title: "Value retrieved",
951+
message: JSON.stringify(result),
952+
okButtonText: "OK"
953+
});
954+
},
955+
error => {
956+
console.log("doGetValueForCompanies error: " + error);
957+
}
958+
);
959+
}
960+
727961
public doUserStoreByPush(): void {
728962
firebase.push(
729963
'/users',

demo/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
}
1010
},
1111
"dependencies": {
12-
"nativescript-plugin-firebase": "../src",
12+
"nativescript-plugin-firebase": "file:../src",
1313
"nativescript-theme-core": "^1.0.4",
1414
"nativescript-unit-test-runner": "^0.3.4",
1515
"tns-core-modules": "^3.3.0"

src/app/auth/index.ts

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import * as firebase from "../../firebase";
2+
import { LoginType, User } from "../../firebase";
3+
4+
export module auth {
5+
export class Auth {
6+
private authStateChangedHandler;
7+
public currentUser: User;
8+
9+
public onAuthStateChanged(handler: (user: User) => void): void {
10+
this.authStateChangedHandler = handler;
11+
console.log(">> added onAuthStateChanged handler");
12+
};
13+
14+
public signOut(): Promise<any> {
15+
return new Promise((resolve, reject) => {
16+
firebase.logout()
17+
.then(() => {
18+
this.currentUser = undefined;
19+
this.authStateChangedHandler && this.authStateChangedHandler();
20+
resolve();
21+
})
22+
.catch(err => {
23+
reject({
24+
// code: "",
25+
message: err
26+
});
27+
});
28+
});
29+
}
30+
31+
public signInWithEmailAndPassword(email: string, password: string): Promise<any> {
32+
return new Promise((resolve, reject) => {
33+
firebase.login({
34+
type: LoginType.PASSWORD,
35+
passwordOptions: {
36+
email: email,
37+
password: password
38+
}
39+
}).then((user: User) => {
40+
this.currentUser = user;
41+
this.authStateChangedHandler && this.authStateChangedHandler(user);
42+
resolve();
43+
}, (err => {
44+
reject({
45+
// code: "",
46+
message: err
47+
});
48+
}));
49+
});
50+
}
51+
52+
public createUserWithEmailAndPassword(email: string, password: string): Promise<any> {
53+
return firebase.createUser({
54+
email: email,
55+
password: password
56+
});
57+
}
58+
59+
public signInAnonymously(): Promise<any> {
60+
return new Promise((resolve, reject) => {
61+
firebase.login({
62+
type: LoginType.ANONYMOUS
63+
}).then((user: User) => {
64+
this.currentUser = user;
65+
this.authStateChangedHandler && this.authStateChangedHandler(user);
66+
resolve();
67+
}, (err => {
68+
reject({
69+
// code: "",
70+
message: err
71+
});
72+
}));
73+
});
74+
}
75+
76+
public fetchProvidersForEmail(email: string): Promise<any> {
77+
return firebase.fetchProvidersForEmail(email);
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)