NativeScript Firebase plugin
The leading realtime app platform (Database, Auth & Hosting). Docs here.
If you can spare 41 seconds, please check this video of the demo app in action:
Use when
- you need to store JSON data in the cloud,
- you want to sync that data to other devices and platforms,
- you want to optionally protect that data by having users log in,
- you want to update clients at the moment the data changes (think chat and multiplayer games).
Prerequisites
Head on over to https://console.firebase.google.com/ and sign up for a free account.
Your first 'Firebase' will be automatically created and made available via a URL like https://n-plugin-test.firebaseio.com
.
Open your Firebase project at the Google console and click 'Add app' to add an iOS and / or Android app.
Follow the steps (make sure the bundle id is the same as your nativescript.id in package.json
and you'll be able to download:
GoogleService-Info.plist
which you'll add to your NativeScript project at app/App_Resources/iOS/GoogleService-Info.plist
google-services.json
which you'll add to your NativeScript project at platforms/android/google-services.json
Installation
From the command prompt go to your app's root folder and execute:
tns plugin add nativescript-plugin-firebase
Usage
If you want a quickstart, clone our demo app (the one in the YouTube video).
And here's the comprehensive list of supported functions:
init
var firebase = require("nativescript-plugin-firebase");
firebase.init({
persist: true
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
All further examples assume firebase
has been required.
Also, all functions support promises, but we're leaving out the .then()
stuff for brevity where it doesn't add value.
setValue
Data is stored as JSON data at a specific path (which is appended to the URL you passed to init
).
If you want to add data to a known path use this, otherwise use push
(see below).
The plugin will take care of serializing JSON data to native data structures.
firebase.setValue(
'/companies',
{'foo':'bar'}
);
firebase.setValue(
'/companies',
[
{name: 'Telerik', country: 'Bulgaria'},
{name: 'Google', country: 'USA'}
]
);
push
This function will store a JSON object at path <Firebase URL>/users/<Generated Key>
firebase.push(
'/users',
{
'first': 'Eddy',
'last': 'Verbruggen',
'birthYear': 1977,
'isMale': true,
'address': {
'street': 'foostreet',
'number': 123
}
}
).then(
function (result) {
console.log("created key: " + result.key);
}
);
query
Firebase supports querying data and this plugin does too, since v2.0.0.
Let's say we have the structure as defined at setValue
, then use this query to retrieve the companies in country 'Bulgaria':
var onQueryEvent = function(result) {
if (!result.error) {
console.log("Event type: " + result.type);
console.log("Key: " + result.key);
console.log("Value: " + JSON.stringify(result.value));
}
};
firebase.query(
onQueryEvent,
"/companies",
{
singleEvent: true,
orderBy: {
type: firebase.QueryOrderByType.CHILD,
value: 'country'
},
range: {
type: firebase.QueryRangeType.EQUAL_TO,
value: 'Bulgaria'
},
limit: {
type: firebase.QueryLimitType.LAST,
value: 2
}
}
);
For supported values of the orderBy/range/limit's type
properties, take a look at the firebase-common.d.ts
TypeScript definitions in this repo.
update
Changes the values of the keys specified in the dictionary without overwriting other keys at this location.
firebase.update(
'/companies',
{'foo':'baz'}
);
addChildEventListener
To listen for changes in your database you can pass in a listener callback function.
You get to control which path inside you database you want to listen to, by default it's /
which is the entire database.
The plugin will take care of serializing native data structures to JSON data.
var onChildEvent = function(result) {
console.log("Event type: " + result.type);
console.log("Key: " + result.key);
console.log("Value: " + JSON.stringify(result.value));
};
firebase.addChildEventListener(onChildEvent, "/users");
addValueEventListener
The difference with addChildEventListener
is explained here.
The link is for the iOS SDK, but it's the same for Android.
var onValueEvent = function(result) {
console.log("Event type: " + result.type);
console.log("Key: " + result.key);
console.log("Value: " + JSON.stringify(result.value));
};
firebase.addValueEventListener(onValueEvent, "/companies");
remove
You can remove the entire database content by passing in '/' as param,
but if you only want to wipe everything at '/users', do this:
firebase.remove("/users");
login
v 1.1.0 of this plugin adds the capability to log your users in. Either anonymously or by email and password.
You need to add support for those features in your Firebase instance at the 'Login & Auth' tab.
You can expect more login mechanisms to be added in the future.
Anonymous login
firebase.login({
type: firebase.LoginType.ANONYMOUS
}).then(
function (result) {
JSON.stringify(result);
},
function (errorMessage) {
console.log(errorMessage);
}
)
Password login
firebase.login({
type: firebase.LoginType.PASSWORD,
email: 'useraccount@provider.com',
password: 'theirpassword'
}).then(
function (result) {
JSON.stringify(result);
},
function (errorMessage) {
console.log(errorMessage);
}
)
Creating a Password account
firebase.createUser({
email: 'eddyverbruggen@gmail.com',
password: 'firebase'
}).then(
function (result) {
dialogs.alert({
title: "User created",
message: "userid: " + result.key,
okButtonText: "Nice!"
})
},
function (errorMessage) {
dialogs.alert({
title: "No user created",
message: errorMessage,
okButtonText: "OK, got it"
})
}
)
Resetting a password
firebase.resetPassword({
email: 'useraccount@provider.com'
}).then(
function () {
},
function (errorMessage) {
console.log(errorMessage);
}
)
Changing a password
firebase.changePassword({
email: 'useraccount@provider.com',
oldPassword: 'myOldPassword',
newPassword: 'myNewPassword'
}).then(
function () {
},
function (errorMessage) {
console.log(errorMessage);
}
)
logout
Shouldn't be more complicated than:
firebase.logout();
Pro tips
See what's happening
It's kinda cool to manipulate data while using multiple devices or your device and the Firebase Dashboard. You will instantly see the update on the other end.
The Firebase Dashboard can be reached by simply loading your Firebase URL in a web browser.
Testing your app in the emulator
tns emulate ios --device "iPhone 6s"
tns emulate android --geny "Nexus 6_23"
or start a geny emulator first and do: tns run android
Future work
- Add support for
removeEventListener
. - Possibly add more login mechanisms.
Credits
The starting point for this plugin was this great Gist by John Bristowe.