Giter Club home page Giter Club logo

fireproof's Introduction

fireproof

A library with some useful utilities for Firebase.

Promise support now deprecated

Firebase 2.4.0 returns Promises without any need for extra help. Hooray!

A celebratory .gif of Sonic the Hedgehog running forever with a rainbow trailing from his butt.

Thanks so much for all your help guys.

Installation

npm install --save fireproof

Usage

See the API documentation here.

The bottom line is this: all Firebase methods are reproduced on a Fireproof object.

By default, Fireproof uses the built-in Promise constructor, which is available in Node > 0.12 and many modern web browsers. You can override this behavior by providing a standards-compliant Promise constructor on Fireproof's constructor, like so:

Fireproof.Promise = require('bluebird');

You can also choose to "bless" Fireproof with a promise library that follows the deferral model:

Fireproof.bless(require('Q'));

If a Promise constructor is not supplied and none exists natively, Fireproof will explode spectacularly.

  • If the corresponding Firebase method has no return value but does something asynchronously, Fireproof returns a promise that fulfills if the interaction succeeds and rejects if an error occurs. This is true of, e.g., transaction(), auth(), set(), update(), remove(), and once().

  • For on(), Firebase returns the callback method that you passed in. Fireproof returns your wrapped callback method with an extra method, then(), attached. So the callback is effectively a promise!

  • For push(), Firebase returns the reference to the new child. Fireproof does the same, but the reference is also a promise that resolves if the push succeeds and rejects if the push fails.

  • All Fireproof objects are themselves promises. Except for the case of push() mentioned above, their then() is a shortcut for fp.once('value'). This means you can get the value of any Fireproof object at any time just by treating it as a promise!

var Fireproof = require('fireproof'),
  Firebase = require('firebase');

var firebase = new Firebase('https://test.firebaseio.com/thing'),
  fireproof = new Fireproof(firebase);

fireproof.auth('my_auth_token').then(function() {
  console.log('Successfully authenticated.')
}, function(err) {
  console.error('Error authenticating to Firebase!');
})

An object encapsulating arrays that keeps their members in sync with a Firebase location's children. The three array references, keys, values, and priorities, are guaranteed to persist for the lifetime of the array. In other words, the arrays themselves are constant; only their contents are mutable. This is highly useful behavior for dirty-checking environments like Angular.js.

Note that changes to the array are not propagated to Firebase.

Usage example:

var Firebase = require('firebase');
var Fireproof = require('fireproof');

var stooges = new Fireproof.LiveArray(function(err) {
  console.error('Hmm, Firebase disconnected with this error: ' + err.message);
});

users.connect(new Firebase('https://my-firebase.firebaseio.com/stooges'));

// some time in the future...
console.log(users.keys);
[
  'larry',
  'curly',
  'moe'
]

console.log(users.values);
[{
  name: 'Curly Howard',
  catchphrase: 'Nyuk-nyuk-nyuk!'
}, {
  name: 'Larry Fine',
  occupation: 'Violinist'
}, {
  name: 'Moe Howard',
  haircut: 'bowl'
}]

console.log(users.priorities);
[1,2,3]

users.disconnect();

JSDocs are inline.

A helper object for paging over Firebase data. You can call next and previous on it with the number of objects to get in the next page, which is expressed as an Array of snapshots.

Usage example:

var Firebase = require('firebase');
var Fireproof = require('fireproof');

var stoogesRef = new Fireproof(new Firebase('https://people.firebaseio-demo.com/stooges'));
var pager = new Fireproof.Pager(stoogesRef);
pager.next(2).then(function(snaps) {
  console.log(snaps.length); // 2
  console.log(snaps[0].child('name').val()); // Curly Howard
  console.log(snaps[1].child('name').val()); // Larry Fine
  return pager.next(2);
})
.then(function(snaps) {
  console.log(snaps.length); // 1
  console.log(snaps[0].child('name').val()); // Moe Howard
  return pager.previous(1);
})
.then(function(snaps) {
  console.log(snaps.length); // 1
  console.log(snaps[0].child('name').val()); // Larry Fine
});

A helper that reports usage data, so you can figure out which Firebase locations you're reading and writing most often.

Usage example:

root.child('foo').set(true)
.then(function() {
  console.log(Fireproof.stats.getPathCounts());
  {
    write: {
      'foo': 1
    }
  }
  
  return root.child('foo');
})
.then(function() {
  console.log(Fireproof.stats.getPathCounts());
  {
    readOnce: {
      'foo': 1
    },
    write: {
      'foo': 1
    }
  }  

  stats.reset();
  console.log(Fireproof.stats.getPathCounts());
  {}
})

See the documentation (linked above) for details. Demux's original purpose was to demultiplex a set of Firebase references into a single event stream for things like feeds, but the way it works isn't really idiomatic with the way Firebase has evolved, and so I don't recommend using it.

Support

IE back to 9.

fireproof's People

Contributors

airdrummingfool avatar aslansky avatar daguej avatar dylanjha avatar goldibex avatar mitranim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fireproof's Issues

Refs incompatible with async/await

Returning a ref from an async function seems to break when the promise is awaited. This is likely do to the regeneratorRuntime checking for Promise-like objects being returned from promises so that they are also awaited. I suppose a temporary work around is to return myRef._ref from any async functions so that there isn't a .then method. Could the return from refs look more like the following?:

let childRef = baseRef.child('child').set('childValue', true);

console.log(childRef);
/* Fireproof {
  _ref: Firebase {...},
  promise: {
    then: function (ok, fail) {...},
    catch: function (err) {...}
  }
} */

This should not be picked up my the regeneratorRuntime's since at the top level it doesn't have any promise methods.

key() not available after calling await ref.push()

After reading the Firebase docs and playing with this repo, I would expect the following to work, but it seems not to:

var ref = fp.child('myref')
var record = await ref.push({ /* some object */})
console.log(record.key()) // This is undefined

I haven't dug into the code yet, but will do so soon. If this does work, please update the README with an example, thanks!

Support Promise#done

If the blessed promise library supplies a done() function, we should make that available on Fireproof instances.

If there is no done, we could probably just alias Fireproof#done to the promise library's then().

`catch` missing when blessed

When blessed, the thing returned from Fireproof is not an actual promise, just an object with a then that is bound to the blessed library's then function. The object is missing the catch method required by ES6 ยง 25.4.5.1.

Ideally, Fireproof would return a real promise from the blessed library. (When un-blessed -- ie using native promises -- it does appear to return real promises.)

I'm pretty sure this is new to 3.1.

Add convenience method to strip promise methods from new refs

Currently new refs created with the push method cannot be resolved in promise chain. Since the return from .push is an object with the prototype of Fireproof and a .then method, returning it from a promise callback will result in it being treated as a promise thus resolving with undefined since .push doesn't have a resolve value.

Temporary work around:

Fireproof.prototype.getRef = function () {
    let ref = new Fireproof(this._ref);
    delete ref.then;
    return ref;
};

Demux doesn't work with corner case of get(1)

When Demux::get() is called with a count of 1, the method returns the same item over and over again and does not advance down the list of Firebase items. Works when Demux::get() is called with any count greater than 1.

typeof(options) === undefined

I was trying to use ref.authAnonymously().then(...) code, and it failed. So, i started debugging it and foud this:

function findOptions(onComplete, options) {
  if (typeof onComplete !== 'function' && typeof(options) === undefined) {
    return onComplete;
  } else {
    return options;
  }
}

Pretty obvious, that typeof(options) will return "undefined" that is string, even when options are not set. This means that condition will never evaluate to true here, so we will receive return options; no matter what we pass as arguments into findOptions.

Interested in project name

Hello, based on the contributors list we may have some mutual acquaintances. I am building a new open-source project called fireproof (it's a database that uses cryptographic proof trees).

Is there any chance I could take over the fireproof npm project name? ๐Ÿฐ Thanks! I can offer the contributors to this project free Fireproof database hosting when it's ready.

Bless breaks with $q in 3.1.0

It seems that catch is no longer attached to the promises:

fireproof.authWithCustomToken(...).catch is not a function

Is this because angular's $q is somehow not spec-compliant?

Promises don't reject when the same promise is returned from a .then resolve

Example:

var firebase = new Firebase(...)
var baseRef = newFireproof(firebase);

function addPost (post) {
  var newPostRef = baseRef.child('post').push(post);
  newPostRef.then(function () {
    newPostRef.child('childRef').set('value', 'something');
    return newPostRef; // If promise and x refer to the same object, reject promise with a TypeError as the reason.
  });
}

addPost({...}).then(function (newPostRef) {
  // use newPostRef
});

Drop the `auth` global lock magic.

From the source:

/*
 * For reasons completely incomprehensible to me, some type of race condition
 * is possible if multiple Fireproof references attempt authentication at the
 * same time, the result of which is one or more of the promises will never
 * resolve.
 * Accordingly, it is necessary that we wrap authentication actions in a
 * global lock. This is accomplished by queuing operations in an array. No, I
 * don't like it any more than you do.
*/

I understand the pain-point you are trying to avoid, but this is a bad idea. It masks the intended behavior of the underlying library.

From the Firebase docs.

All Firebase references to the same database share the same authentication status, so if you call new Firebase("https://.firebaseio.com/") twice and call any authentication method on one of them, they will both be authenticated.

If you point your ref's at two different firebase base URL's (https://firebase1.firebaseio.test, and https://firebase2.firebaseio.test), you should be able to authenticate both of those concurrently without the odd behavior.

You really should not be calling auth twice (concurrently) in your code. If you are it is probably an error. The authorization token from the second call will be used to authenticate the first - even if you have created separate ref instances.

If you really want to avoid this behavior, you can use firebase-copy, which gives you a new Firebase constructors each time, with its own set of global state. In addition to avoiding the auth idiosyncrasies that are frustrating you here, it also improves some client side code testing by ensuring async behavior behavior between ref.set and ref.on('value', listener)

var firebaseCopy = require('firebase-copy');

var Firebase1 = firebaseCopy();
var Firebase2 = firebaseCopy();

var ref1 = new Firebase1(URL);
var ref2 = new Firebase2(URL);

ref1.on('value', listener1);
ref2.on('value', listener2);

ref1.set(newValue);
// => listener1 will trigger synchronously (before roundtrip to server, potentially triggered twice if write is denied).
// => listener2 will fire once asynchronously (after roundtrip to server. Potentially never triggered if write is denied).

I do not recommend firebase-copy for production, just testing.

The global state behavior of Firebase is intentional. It is better to structure your app to deal with those idiosyncrasies directly than trying to hide them.

Should fireproof resolve on `then`?

First of all, thanks for this library, very nice.

A question: I have a function call that returns a promise which I resolve with a Fireproof, which I then plan to use to run a on('child_added') query or something similar. However, returning the Fireproof as part of a promise chain means that the .then of the Fireproof object gets called, and I end up with a snapshot instead:

function getFireproof() {
  return doSomething()
    .then(() => {
      return new Fireproof(new Firebase('firebase.io/whatever'));
    });
}

getFireproof()
  .on('child_added')  //explodes here because it's getting a snapshot val back
  .then(doSomething);

Is there a nicer way to do this that I'm missing in the API? I can get around it by hacking out the .then from the Fireproof instance, but that's not ideal.

Fireproof return variables

Below is the working code to access data form firebase. It uses global variable 'Data' array to send it to the final callback function. But I don't want to declare global variable. So is there anyway I can pass my data to every callbacks after it ? below is the code.

var data = {};

getData('myKey', function(){
console.log("myCompleteData: "+ data); //both Id and finalData
});

var getData= function(key,callback) {
return fireproof.child("data").child(key)
.then(CUSTOM_getData)
.then(callback)
}

function CUSTOM_getData(snapshot) {

    var id= snapshot.val().id;
    data.id= id;

return {
then: function(callback) {

fireproof.child("otherData").child(data.id)
.then(CUSTOM_getSomethingFromId)
.then(callback)
  }

};
}

function CUSTOM_getSomethingFromId(snapshot) {

        var finalData = snapshot.val().finalData;
        data.finalData = finalData;

  return {
    then: function(callback) {

    callback(data);
      }  
  };

}

Doesn't support native promises

Now that Promise is standard JavaScript I don't see any reason to fall back to Q promises. Native promises are much easier to debug.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.