Merge pull request #3109 from in-async/firebase.d.ts

update firebase/firebase.d.ts to version 2.0.2
This commit is contained in:
Masahiro Wakame
2014-11-29 13:53:16 +09:00
3 changed files with 1075 additions and 47 deletions

View File

@@ -20,8 +20,8 @@ interface AngularFire {
$remove(key?: string): ng.IPromise<Firebase>;
$update(key: string, data: Object): ng.IPromise<Firebase>;
$update(data: any): ng.IPromise<Firebase>;
$transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<IFirebaseDataSnapshot>;
$transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<IFirebaseDataSnapshot>;
$transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
$transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
}
interface AngularFireObject extends AngularFireSimpleObject {

View File

@@ -11,6 +11,152 @@ dataRef.auth(AUTH_TOKEN, function(error, result) {
}
});
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com/');
/*
* Firebase.authWithCustomToken()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithCustomToken(AUTH_TOKEN, function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authAnonymously()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authAnonymously(function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authWithPassword()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithPassword({
"email": "bobtony@firebase.com",
"password": "correcthorsebatterystaple"
}, function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authWithOAuthPopup()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithOAuthPopup("twitter", function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.authWithOAuthRedirect
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Log me in
dataRef.authWithOAuthRedirect("twitter", function (error) {
if (error) {
console.log('Login Failed!', error);
} else {
// We'll never get here, as the page will redirect on success.
}
});
}
/*
* Firebase.authWithOAuthToken()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Authenticate with Facebook using an existing OAuth 2.0 access token
dataRef.authWithOAuthToken("facebook", "<ACCESS-TOKEN>", function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
// Authenticate with Twitter using an existing OAuth 1.0a credential set
dataRef.authWithOAuthToken("twitter", {
"user_id": "<USER-ID>",
"oauth_token": "<ACCESS-TOKEN>",
"oauth_token_secret": "<ACCESS-TOKEN-SECRET>",
}, function (error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}
/*
* Firebase.getAuth()
*/
() => {
var dataRef = new Firebase('https://samplechat.firebaseio-demo.com');
var authData = dataRef.getAuth();
if (authData) {
console.log('Authenticated user with uid:', authData.uid);
}
}
/*
* Firebase.onAuth()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.onAuth(function (authData) {
if (authData) {
console.log('Client is authenticated with uid ' + authData.uid);
} else {
// Client is unauthenticated
}
});
}
/*
* Firebase.offAuth
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
var onAuthChange = function (authData: FirebaseAuthData) { /*...*/ };
firebaseRef.onAuth(onAuthChange);
// Sometime later...
firebaseRef.offAuth(onAuthChange);
}
//Time to log out!
dataRef.unauth();
@@ -36,6 +182,146 @@ var fredRef3:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/use
var x4:string = fredRef3.name();
// x is now 'fred'.
/*
* Firebase.key()
*/
() => {
var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred");
var key = fredRef.key(); // key === "fred"
key = fredRef.child("name/last").key(); // key === "last"
}
() => {
// Calling key() on the root of a Firebase will return null:
var rootRef = new Firebase("https://samplechat.firebaseio-demo.com");
var key = rootRef.key(); // key === null
}
/*
* Firebase.set()
*/
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
fredNameRef.child('first').set('Fred');
fredNameRef.child('last').set('Flintstone');
// We've written 'Fred' to the Firebase location storing fred's first name,
// and 'Flintstone' to the location storing his last name
}
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
fredNameRef.set({ first: 'Fred', last: 'Flintstone' });
// Exact same effect as the previous example, except we've written
// fred's first and last name simultaneously
}
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
var onComplete = function (error: any) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
fredNameRef.set({ first: 'Fred', last: 'Flintstone' }, onComplete);
// Same as the previous example, except we will also log a message
// when the data has finished synchronizing
}
/*
* Firebase.update()
*/
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
// Modify the 'first' and 'last' children, but leave other data at fredNameRef unchanged
fredNameRef.update({ first: 'Fred', last: 'Flintstone' });
}
() => {
var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name');
// Same as the previous example, except we will also display an alert
// message when the data has finished synchronizing.
var onComplete = function (error:any) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
fredNameRef.update({ first: 'Wilma', last: 'Flintstone' }, onComplete);
}
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
//The following 2 function calls are equivalent
fredRef.update({ name: { first: 'Fred', last: 'Flintstone' }});
fredRef.child('name').set({ first: 'Fred', last: 'Flintstone' });
}
/*
* Firebase.remove()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
fredRef.remove();
// All data at the Firebase location for user 'fred' has been deleted
// (including any child data)
}
() => {
var onComplete = function (error: any) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
fredRef.remove(onComplete);
// Same as the previous example, except we will also log
// a message when the delete has finished synchronizing
}
/*
* Firebase.push()
*/
() => {
var messageListRef = new Firebase('https://samplechat.firebaseio-demo.com/message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
// We've appended a new message to the message_list location.
var path = newMessageRef.toString();
// path will be something like
// 'https://samplechat.firebaseio-demo.com/message_list/-IKo28nwJLH0Nc5XeFmj'
}
() => {
var messageListRef = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
messageListRef.push({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
// Same effect as the previous example, but we've combined the push() and the set().
}
/*
* Firebase.setWithPriority()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
var user = {
name: {
first: 'Fred',
last: 'Flintstone'
},
rank: 1000
};
fredRef.setWithPriority(user, 1000);
// We've written Fred's name and rank to firebase, and used his rank (1000) as the
// priority of the data so he'll be ordered relative to other users by his rank
}
/*
* Firebase.setPriority()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
fredRef.setPriority(1000);
// We have changed the priority of fred's user data to 1000
}
// Increment Fred's rank by 1.
var fredRankRef:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred/rank');
fredRankRef.transaction(function(currentRank: number) {
@@ -51,7 +337,7 @@ wilmaRef.transaction(function(currentData) {
console.log('User wilma already exists.');
return; // Abort the transaction.
}
}, function(error: any, committed: boolean, snapshot: IFirebaseDataSnapshot) {
}, function(error: any, committed: boolean, snapshot: FirebaseDataSnapshot) {
if (error)
console.log('Transaction failed abnormally!', error);
else if (!committed)
@@ -61,14 +347,523 @@ wilmaRef.transaction(function(currentData) {
console.log('Wilma\'s data: ', snapshot.val());
});
var messageListRef: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
var lastMessagesQuery:IFirebaseQuery = messageListRef.endAt().limit(500);
lastMessagesQuery.on('child_added', function(childSnapshot: IFirebaseDataSnapshot) { /* handle child add */ });
/*
* Firebase.createUser()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.createUser({
email: "bobtony@firebase.com",
password: "correcthorsebatterystaple"
}, function (err) {
if (err) {
switch (err.code) {
case 'EMAIL_TAKEN':
// The new user account cannot be created because the email is already in use.
case 'INVALID_EMAIL':
// The specified email is not a valid email.
default:
}
} else {
// User account created successfully!
}
});
}
var messageListRef2:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
var firstMessagesQuery:IFirebaseQuery = messageListRef2.startAt().limit(500);
firstMessagesQuery.on('child_added', function(childSnapshot: IFirebaseDataSnapshot) { /* handle child add */ });
/*
* Firebase.changePassword()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.changePassword({
email: "bobtony@firebase.com",
oldPassword: "correcthorsebatterystaple",
newPassword: "shinynewpassword"
}, function (err) {
if (err) {
switch (err.code) {
case 'INVALID_PASSWORD':
// The specified user account password is incorrect.
case 'INVALID_USER':
// The specified user account does not exist.
default:
}
} else {
// User password changed successfully!
}
});
}
var usersRef3: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users');
var usersQuery: IFirebaseQuery = usersRef3.startAt(1000).limit(50);
usersQuery.on('child_added', function(userSnapshot: IFirebaseDataSnapshot) { /* handle user */ });
/*
* Firebase.removeUser()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.removeUser({
email: "bobtony@firebase.com",
password: "correcthorsebatterystaple"
}, function (err) {
if (err) {
switch (err.code) {
case 'INVALID_USER':
// The specified user account does not exist.
case 'INVALID_PASSWORD':
// The specified user account password is incorrect.
default:
}
} else {
// User account deleted successfully!
}
});
}
/*
* Firebase.resetPassword()
*/
() => {
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.resetPassword({
email: "bobtony@firebase.com"
}, function (err) {
if (err) {
switch (err.code) {
case 'INVALID_USER':
// The specified user account does not exist.
default:
}
} else {
// Password reset email sent successfully!
}
});
}
//var messageListRef: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
//var lastMessagesQuery:FirebaseQuery = messageListRef.endAt().limit(500);
//lastMessagesQuery.on('child_added', function(childSnapshot: FirebaseDataSnapshot) { /* handle child add */ });
//var messageListRef2:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
//var firstMessagesQuery:FirebaseQuery = messageListRef2.startAt().limit(500);
//firstMessagesQuery.on('child_added', function(childSnapshot: FirebaseDataSnapshot) { /* handle child add */ });
//var usersRef3: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users');
//var usersQuery: FirebaseQuery = usersRef3.startAt(1000).limit(50);
//usersQuery.on('child_added', function(userSnapshot: FirebaseDataSnapshot) { /* handle user */ });
/*
* Firebase.goOffline()
* Firebase.goOnline()
*/
() => {
var usersRef = new Firebase('https://samplechat.firebaseio-demo.com/users');
Firebase.goOffline(); // All Firebase instances are disconnected
Firebase.goOnline(); // All Firebase instances automatically reconnect
}
/*
* FirebaseQuery.on()
*/
() => {
firebaseRef.on('value', function (dataSnapshot) {
// code to handle new value.
});
firebaseRef.on('child_added', function (childSnapshot, prevChildName) {
// code to handle new child.
});
firebaseRef.on('child_removed', function (oldChildSnapshot) {
// code to handle child removal.
});
firebaseRef.on('child_changed', function (childSnapshot, prevChildName) {
// code to handle child data changes.
});
firebaseRef.on('child_changed', function (childSnapshot, prevChildName) {
// code to handle child data changes.
});
}
/*
* FirebaseQuery.off()
*/
() => {
var onValueChange = function (dataSnapshot: FirebaseDataSnapshot) { /* handle... */ };
firebaseRef.on('value', onValueChange);
// Sometime later...
firebaseRef.off('value', onValueChange);
}
() => {
// Or you can save a line of code by using an inline function
// and on()'s return value.
var onValueChange = firebaseRef.on('value', function (dataSnapshot) { /* handle... */ });
// Sometime later...
firebaseRef.off('value', onValueChange);
}
/*
* FirebaseQuery.once()
*/
() => {
// Basic usage of .once() to read the data located at firebaseRef.
firebaseRef.once('value', function (dataSnapshot) {
// handle read data.
});
}
() => {
// Provide a failureCallback to be notified when this
// callback is revoked due to security violations.
firebaseRef.once('value', function (dataSnapshot) {
// code to handle new value
}, function (err: any) {
// code to handle read error
});
}
() => {
// Provide a context to override "this" when callbacks are triggered.
firebaseRef.once('value', function (dataSnapshot) {
// this.x is 1
}, { x: 1 });
}
/*
* FirebaseQuery.orderByChild()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can read all dinosaurs ordered by height using the following query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").on("child_added", function (snapshot) {
console.log(snapshot.key() + " was " + snapshot.val().height + " meters tall");
});
}
/*
* FirebaseQuery.orderByKey()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can read all dinosaurs in alphabetical order, ignoring their priority,
// using the following query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByKey().on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.orderByPriority()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can read all dinosaurs in priority order using the following query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByPriority().on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.startAt()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can find all dinosaurs that are at least three meters tall
// by combining orderByChild() and startAt():
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").startAt(3).on("child_added", function (snapshot) {
console.log(snapshot.key())
});
}
/*
* FirebaseQuery.endAt()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can find all dinosaurs whose names come before Pterodactyl lexicographically
// by combining orderByKey() and endAt():
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByKey().endAt("pterodactyl").on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.equalTo()
*/
() => {
// For example, using our sample Firebase of dinosaur facts,
// we can find all dinosaurs whose height is exactly 25 meters
// by combining orderByChild() and equalTo():
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").equalTo(25).on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.limitToFirst
*/
() => {
// Using our sample Firebase of dinosaur facts,
// we can find the two shortest dinosaurs with this query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("height").limitToFirst(2).on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.limitToLast
*/
() => {
// Using our sample Firebase of dinosaur facts,
// we can find the two heaviest dinosaurs with this query:
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/");
ref.orderByChild("weight").limitToLast(2).on("child_added", function (snapshot) {
console.log(snapshot.key());
});
}
/*
* FirebaseQuery.ref()
*/
() => {
// The Firebase reference returned by ref() is equivalent to the Firebase reference used to create the Query.
var ref = new Firebase("https://samplechat.firebaseio-demo.com/users");
var query = ref.limitToFirst(5);
var refToSameLocation = query.ref(); // ref === refToSameLocation
}
/*
* Firebase.onDisconnect().set()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectmessage');
disconnectRef.onDisconnect().set('I disconnected!');
}
/*
* Firebase.onDisconnect().update()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectmessage');
disconnectRef.onDisconnect().update({ message: 'I disconnected!' });
}
/*
* Firebase.onDisconnect().remove()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectdata');
disconnectRef.onDisconnect().remove();
}
/*
* Firebase.onDisconnect().setWithPriority()
*/
() => {
var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectMessage');
disconnectRef.onDisconnect().setWithPriority('I disconnected', 10);
}
/*
* Firebase.onDisconnect().cancel()
*/
() => {
var fredOnlineRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/online');
fredOnlineRef.onDisconnect().set(false);
// cancel the previously set onDisconnect().set() event
fredOnlineRef.onDisconnect().cancel();
}
/*
* Firebase.ServerValue.TIMESTAMP
*/
() => {
// Record the current time immediately, and queue an event to
// record the time at which the user disconnects.
var sessionsRef = new Firebase('https://samplechat.firebaseio-demo.com/sessions/');
var mySessionRef = sessionsRef.push();
mySessionRef.onDisconnect().update({ endedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
}
/*
* DataSnapshot.val()
*/
() => {
// Demonstrate writing data and then reading it back as a Javascript object.
var fredNameRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred');
fredNameRef.set({ first: 'Fred', last: 'Flintstone' });
fredNameRef.once('value', function (nameSnapshot) {
var val = nameSnapshot.val();
// val now contains the object { first: 'Fred', last: 'Flintstone' }.
});
}
/*
* DataSnapshot.child()
*/
(dataSnapshot:FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child 'name' that has children 'first'
// (set to 'Fred') and 'last' (set to 'Flintstone'):
var nameSnapshot = dataSnapshot.child('name');
var name = nameSnapshot.val();
// name now contains { first: 'Fred', last: 'Flintstone'}.
var firstNameSnapshot = dataSnapshot.child('name/first');
var firstName = firstNameSnapshot.val();
// firstName now contains 'Fred'.
var favoriteColorSnapshot = dataSnapshot.child('favorite_color');
var favoriteColor = favoriteColorSnapshot.val();
// favoriteColor will be null, because there is no 'favorite_color' child in dataSnapshot.
}
/*
* DataSnapshot.forEach()
*/
(dataSnapshot:FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child "fred" and a child "wilma", this callback
// function will be called twice
dataSnapshot.forEach(function (childSnapshot) {
// key will be "fred" the first time and "wilma" the second time
var key = childSnapshot.key();
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
}
(dataSnapshot:FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child "fred" and a child "wilma", this callback
// funciton will only be called once (since we return true)
dataSnapshot.forEach(function (childSnapshot) {
var key = childSnapshot.key(); // key will be "fred"
return true;
});
}
/*
* DataSnapshot.hasChild()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a DataSnapshot with child 'fred' and no other children:
var x = dataSnapshot.hasChild('fred');
var y = dataSnapshot.hasChild('whales');
// x is true and y is false.
}
/*
* DataSnapshot.hasChildren()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child 'name' with children 'first'
// (set to 'Fred') and 'last' (set to 'Flintstone'):
var x = dataSnapshot.hasChildren();
// x is true.
var y = dataSnapshot.child('name').hasChildren();
// y is true.
var z = dataSnapshot.child('name/first').hasChildren();
// z is false since 'Fred' is a string and therefore has no children.
}
/*
* DataSnapshot.key()
*/
() => {
// Calling key() on any DataSnapshot (except for one which represents the root of a Firebase)
// will return the key name of the location that generated it:
var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred");
fredRef.on("value", function (fredSnapshot) {
var key = fredSnapshot.key(); // key === "fred"
key = fredSnapshot.child("name/last").key(); // key === "last"
});
}
() => {
// Calling key() on a DataSnapshot generated from a reference to the root of a Firebase return null:
var rootRef = new Firebase("https://samplechat.firebaseio-demo.com");
rootRef.on("value", function (rootSnapshot) {
var key = rootSnapshot.key(); // key === null
});
}
/*
* DataSnapshot.name()
*/
() => {
var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred");
fredRef.on("value", function (fredSnapshot) {
var key = fredSnapshot.name(); // key === "fred"
key = fredSnapshot.child("name/last").name(); // key === "last"
});
}
() => {
var rootRef = new Firebase("https://samplechat.firebaseio-demo.com");
rootRef.on("value", function (rootSnapshot) {
var key = rootSnapshot.name(); // key === null
});
}
/*
* DataSnapshot.numChildren()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a DataSnapshot containing a child 'name' with children 'first'
// (set to 'Fred') and 'last' (set to 'Flintstone'):
var x = dataSnapshot.numChildren();
// x is 1.
var y = dataSnapshot.child('name').numChildren();
// y is 2.
var z = dataSnapshot.child('name/first').numChildren();
// z is 0 since 'Fred' is a string and therefore has no children.
}
/*
* DataSnaphot.ref()
*/
() => {
var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred');
fredRef.on('value', function (fredSnapshot) {
var fredRef2 = fredSnapshot.ref();
// fredRef and fredRef2 both point to the same location.
});
}
/*
* DataSnapshot.getPriority()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
// Given a snapshot for data with priority 1000:
var x = dataSnapshot.getPriority();
// x is now 1000.
}
/*
* DataSnapshot.exportVal()
*/
(dataSnapshot: FirebaseDataSnapshot) => {
firebaseRef.setWithPriority('hello', 500);
firebaseRef.once('value', function (dataSnapshot) {
var x = dataSnapshot.exportVal();
// x now contains { '.value': 'hello', '.priority': 500 }
});
}
(dataSnapshot: FirebaseDataSnapshot) => {
firebaseRef.set('hello');
firebaseRef.once('value', function (dataSnapshot) {
var x = dataSnapshot.exportVal();
// x now contains 'hello'
});
}
(dataSnapshot: FirebaseDataSnapshot) => {
// Note: To access these variables in JavaScript, you can use x['.value'] and x['.priority'].
firebaseRef.setWithPriority({ a: 'hello', b: 'hi' }, 500);
firebaseRef.once('value', function (dataSnapshot) {
var x = dataSnapshot.exportVal();
// x now contains { 'a': 'hello', 'b': 'hi', '.priority': 500 }
});
}

303
firebase/firebase.d.ts vendored
View File

@@ -1,75 +1,308 @@
// Type definitions for Firebase API
// Type definitions for Firebase API 2.0.2
// Project: https://www.firebase.com/docs/javascript/firebase
// Definitions by: Vincent Botone <https://github.com/vbortone/>
// Definitions by: Vincent Botone <https://github.com/vbortone/>, Shin1 Kashimura <https://github.com/in-async/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface IFirebaseAuthResult {
interface FirebaseAuthResult {
auth: any;
expires: number;
}
interface IFirebaseDataSnapshot {
interface FirebaseDataSnapshot {
/**
* Gets the JavaScript object representation of the DataSnapshot.
*/
val(): any;
child(childPath: string): IFirebaseDataSnapshot;
forEach(childAction: (childSnapshot: IFirebaseDataSnapshot) => boolean): boolean;
/**
* Gets a DataSnapshot for the location at the specified relative path.
*/
child(childPath: string): FirebaseDataSnapshot;
/**
* Enumerates through the DataSnapshots children (in the default order).
*/
forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => void): boolean;
forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => boolean): boolean;
/**
* Returns true if the specified child exists.
*/
hasChild(childPath: string): boolean;
/**
* Returns true if the DataSnapshot has any children.
*/
hasChildren(): boolean;
/**
* Gets the key name of the location that generated this DataSnapshot.
*/
key(): string;
/**
* @deprecated Use key() instead.
* Gets the key name of the location that generated this DataSnapshot.
*/
name(): string;
/**
* Gets the number of children for this DataSnapshot.
*/
numChildren(): number;
/**
* Gets the Firebase reference for the location that generated this DataSnapshot.
*/
ref(): Firebase;
/**
* Gets the priority of the data in this DataSnapshot.
* @returns {string, number, null} The priority, or null if no priority was set.
*/
getPriority(): any; // string or number
/**
* Exports the entire contents of the DataSnapshot as a JavaScript object.
*/
exportVal(): Object;
}
interface IFirebaseOnDisconnect {
interface FirebaseOnDisconnect {
/**
* Ensures the data at this location is set to the specified value when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
set(value: any, onComplete?: (error: any) => void): void;
/**
* Ensures the data at this location is set to the specified value and priority when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void;
setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void;
update(value: any, onComplete?: (error: any) => void): void;
/**
* Writes the enumerated children at this Firebase location when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
update(value: Object, onComplete?: (error: any) => void): void;
/**
* Ensures the data at this location is deleted when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*/
remove(onComplete?: (error: any) => void): void;
/**
* Cancels all previously queued onDisconnect() set or update events for this location and all children.
*/
cancel(onComplete?: (error: any) => void): void;
}
interface IFirebaseQuery {
on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void;
off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void;
once(eventType: string, successCallback: (dataSnapshot: IFirebaseDataSnapshot) => void, failureCallback?: () => void, context?: Object): void;
limit(limit: number): IFirebaseQuery;
startAt(priority?: string, name?: string): IFirebaseQuery;
startAt(priority?: number, name?: string): IFirebaseQuery;
endAt(priority?: string, name?: string): IFirebaseQuery;
endAt(priority?: number, name?: string): IFirebaseQuery;
interface FirebaseQuery {
/**
* Listens for data changes at a particular location.
*/
on(eventType: string, callback: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: (error: any) => void, context?: Object): (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void;
/**
* Detaches a callback previously attached with on().
*/
off(eventType?: string, callback?: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void;
/**
* Listens for exactly one event of the specified event type, and then stops listening.
*/
once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, context?: Object): void;
once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, failureCallback?: (error: any) => void, context?: Object): void;
/**
* Generates a new Query object ordered by the specified child key.
*/
orderByChild(key: string): FirebaseQuery;
/**
* Generates a new Query object ordered by key name.
*/
orderByKey(): FirebaseQuery;
/**
* Generates a new Query object ordered by priority.
*/
orderByPriority(): FirebaseQuery;
/**
* @deprecated Use limitToFirst() and limitToLast() instead.
* Generates a new Query object limited to the specified number of children.
*/
limit(limit: number): FirebaseQuery;
/**
* Creates a Query with the specified starting point.
* The generated Query includes children which match the specified starting point.
*/
startAt(value: string, key?: string): FirebaseQuery;
startAt(value: number, key?: string): FirebaseQuery;
/**
* Creates a Query with the specified ending point.
* The generated Query includes children which match the specified ending point.
*/
endAt(value: string, key?: string): FirebaseQuery;
endAt(value: number, key?: string): FirebaseQuery;
/**
* Creates a Query which includes children which match the specified value.
*/
equalTo(value: string, key?: string): FirebaseQuery;
equalTo(value: number, key?: string): FirebaseQuery;
/**
* Generates a new Query object limited to the first certain number of children.
*/
limitToFirst(limit: number): FirebaseQuery;
/**
* Generates a new Query object limited to the last certain number of children.
*/
limitToLast(limit: number): FirebaseQuery;
/**
* Gets a Firebase reference to the Query's location.
*/
ref(): Firebase;
}
declare class Firebase implements IFirebaseQuery {
constructor(firebaseURL: string);
auth(authToken: string, onComplete?: (error: any, result: IFirebaseAuthResult) => void, onCancel?:(error: any) => void): void;
interface Firebase extends FirebaseQuery {
/**
* @deprecated Use authWithCustomToken() instead.
* Authenticates a Firebase client using the provided authentication token or Firebase Secret.
*/
auth(authToken: string, onComplete?: (error: any, result: FirebaseAuthResult) => void, onCancel?:(error: any) => void): void;
/**
* Authenticates a Firebase client using an authentication token or Firebase Secret.
*/
authWithCustomToken(autoToken: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?:Object): void;
/**
* Authenticates a Firebase client using a new, temporary guest account.
*/
authAnonymously(onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Authenticates a Firebase client using an email / password combination.
*/
authWithPassword(credentials: FirebaseCredentials, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Authenticates a Firebase client using a popup-based OAuth flow.
*/
authWithOAuthPopup(provider: string, onComplete:(error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Authenticates a Firebase client using a redirect-based OAuth flow.
*/
authWithOAuthRedirect(provider: string, onComplete: (error: any) => void, options?: Object): void;
/**
* Authenticates a Firebase client using OAuth access tokens or credentials.
*/
authWithOAuthToken(provider: string, credentials: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
authWithOAuthToken(provider: string, credentials: Object, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void;
/**
* Synchronously access the current authentication state of the client.
*/
getAuth(): FirebaseAuthData;
/**
* Listen for changes to the client's authentication state.
*/
onAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void;
/**
* Detaches a callback previously attached with onAuth().
*/
offAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void;
/**
* Unauthenticates a Firebase client.
*/
unauth(): void;
/**
* Gets a Firebase reference for the location at the specified relative path.
*/
child(childPath: string): Firebase;
/**
* Gets a Firebase reference to the parent location.
*/
parent(): Firebase;
/**
* Gets a Firebase reference to the root of the Firebase.
*/
root(): Firebase;
/**
* Returns the last token in a Firebase location.
*/
key(): string;
/**
* @deprecated Use key() instead.
* Returns the last token in a Firebase location.
*/
name(): string;
/**
* Gets the absolute URL corresponding to this Firebase reference's location.
*/
toString(): string;
/**
* Writes data to this Firebase location.
*/
set(value: any, onComplete?: (error: any) => void): void;
update(value: any, onComplete?: (error: any) => void): void;
/**
* Writes the enumerated children to this Firebase location.
*/
update(value: Object, onComplete?: (error: any) => void): void;
/**
* Removes the data at this Firebase location.
*/
remove(onComplete?: (error: any) => void): void;
push(value: any, onComplete?: (error: any) => void): Firebase;
/**
* Generates a new child location using a unique name and returns a Firebase reference to it.
* @returns {Firebase} A Firebase reference for the generated location.
*/
push(value?: any, onComplete?: (error: any) => void): Firebase;
/**
* Writes data to this Firebase location. Like set() but also specifies the priority for that data.
*/
setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void;
setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void;
/**
* Sets a priority for the data at this Firebase location.
*/
setPriority(priority: string, onComplete?: (error: any) => void): void;
setPriority(priority: number, onComplete?: (error: any) => void): void;
transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: IFirebaseDataSnapshot) => void, applyLocally?: boolean): void;
onDisconnect(): IFirebaseOnDisconnect;
on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void;
off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void;
once(eventType: string, successCallback: (dataSnapshot: IFirebaseDataSnapshot) => void, failureCallback?: () => void, context?: Object): void;
limit(limit: number): IFirebaseQuery;
startAt(priority?: string, name?: string): IFirebaseQuery;
startAt(priority?: number, name?: string): IFirebaseQuery;
endAt(priority?: string, name?: string): IFirebaseQuery;
endAt(priority?: number, name?: string): IFirebaseQuery;
ref(): Firebase;
goOffline(): void;
goOnline(): void;
/**
* Atomically modifies the data at this location.
*/
transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: FirebaseDataSnapshot) => void, applyLocally?: boolean): void;
/**
* Creates a new user account using an email / password combination.
*/
createUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void;
/**
* Change the password of an existing user using an email / password combination.
*/
changePassword(credentials: { email: string; oldPassword: string; newPassword: string }, onComplete: (error: any) => void): void;
/**
* Removes an existing user account using an email / password combination.
*/
removeUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void;
/**
* Sends a password-reset email to the owner of the account, containing a token that may be used to authenticate and change the user password.
*/
resetPassword(credentials: { email: string }, onComplete: (error: any) => void): void;
onDisconnect(): FirebaseOnDisconnect;
}
interface FirebaseStatic {
/**
* Constructs a new Firebase reference from a full Firebase URL.
*/
new (firebaseURL: string): Firebase;
/**
* Manually disconnects the Firebase client from the server and disables automatic reconnection.
*/
goOffline(): void;
/**
* Manually reestablishes a connection to the Firebase server and enables automatic reconnection.
*/
goOnline(): void;
ServerValue: {
/**
* A placeholder value for auto-populating the current timestamp
* (time since the Unix epoch, in milliseconds) by the Firebase servers.
*/
TIMESTAMP: any;
};
}
declare var Firebase: FirebaseStatic;
// Reference: https://www.firebase.com/docs/web/api/firebase/getauth.html
interface FirebaseAuthData {
uid: string;
provider: string;
token: string;
expires: number;
auth: Object;
}
interface FirebaseCredentials {
email: string;
password: string;
}