Skip to content

Instantly share code, notes, and snippets.

@guibot17
guibot17 / firebase_first_item.js
Last active September 15, 2015 19:19 — forked from anantn/firebase_first_item.js
Firebase: Get the first item in a list. This snippet retrieves only the first item in a list.
function makeList(ref) {
var fruits = ["banana", "apple", "grape", "orange"];
for (var i = 0; i < fruits.length; i++) {
ref.push(fruits[i]);
}
}
function getFirstFromList(ref, cb) {
ref.startAt().limit(1).once("child_added", function(snapshot) {
cb(snapshot.val());
@guibot17
guibot17 / 1_query_timestamp.js
Last active September 15, 2015 19:15 — forked from katowulf/1_query_timestamp.js
Get only new items from Firebase
// assumes you add a timestamp field to each record (see Firebase.ServerValue.TIMESTAMP)
// pros: fast and done server-side (less bandwidth, faster response), simple
// cons: a few bytes on each record for the timestamp
var ref = new Firebase(...);
ref.orderByChild('timestamp').startAt(Date.now()).on('child_added', function(snapshot) {
console.log('new record', snap.key());
});
@guibot17
guibot17 / jwtparser.js
Last active September 15, 2015 19:10 — forked from katowulf/jwtparser.js
Deconstruct a JWT token for Firebase
// Helper function to extract claims from a JWT. Does *not* verify the
// validity of the token.
// credits: https://github.com/firebase/angularFire/blob/master/angularFire.js#L370
// polyfill window.atob() for IE8: https://github.com/davidchambers/Base64.js
// or really fast Base64 by Fred Palmer: https://code.google.com/p/javascriptbase64/
function deconstructJWT(token) {
var segments = token.split(".");
if (!segments instanceof Array || segments.length !== 3) {
throw new Error("Invalid JWT");
}
@guibot17
guibot17 / firebase_create.js
Last active September 15, 2015 19:08 — forked from anantn/firebase_create.js
Firebase: Creating data if it doesn't exist. This snippet creates a user only if it doesn't already exist.
function go() {
var userId = prompt('Username?', 'Guest');
var userData = { name: userId };
tryCreateUser(userId, userData);
}
var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
function userCreated(userId, success) {
if (!success) {
@guibot17
guibot17 / firebase_player_assignment.js
Last active September 15, 2015 19:05 — forked from anantn/firebase_player_assignment.js
Firebase: Assigning players in a multiplayer game. This snippet assigns you a spot in a game if the game isn't full yet.
function go() {
var userId = prompt('Username?', 'Guest');
// Consider adding '/<unique id>' if you have multiple games.
var gameRef = new Firebase(GAME_LOCATION);
assignPlayerNumberAndPlayGame(userId, gameRef);
};
// The maximum number of players. If there are already
// NUM_PLAYERS assigned, users won't be able to join the game.
var NUM_PLAYERS = 4;