angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

0.8.0 doesn't save date objects

Open joshbowdoin opened this issue 12 years ago • 18 comments

Previously AngularFire (0.7.1) called angular.fromJson(angular.toJson(record)) before a save, which converted date objects to JSON dates. Could this be added back as the last line of firebaseUtils.toJSON()?

As it stands now, I have to handle each date before the save, otherwise they are simply omitted (no errors or anything). Or am I missing something?

joshbowdoin avatar Aug 05 '14 18:08 joshbowdoin

Add a toJSON method on the objects and you can transform them however you like before save. You could also decorate toJSON.

$FirebaseObject.$extendFactory({
    toJSON: function() {
       return { foo: this.foo, bar: this.baz.valueOf() };
   }
});
app.config(function($provide) {
    $provide.decorator('$firebaseUtils', function($delegate) {
       var _super = $delegate.toJSON;
      $delegate.toJSON = function(rec) {
          var json = _super(rec);
          return angular.fromJson(angular.toJson(record));
      };
       return $delegate;
   });
});

katowulf avatar Aug 05 '14 20:08 katowulf

OK, I like the decorator option. Is there a reason you don't want this in the library?

joshbowdoin avatar Aug 05 '14 20:08 joshbowdoin

I haven't thought through all the implications of putting that into the core. I'll ponder and discuss with Jacob before we opine on whether it's a good choice.

katowulf avatar Aug 05 '14 20:08 katowulf

OK.

joshbowdoin avatar Aug 05 '14 20:08 joshbowdoin

We talked this over today and decided that this is too ambiguous to handle at the API level.

If we modify the toJSON method to convert dates, should they use strings or epoch timestamps? (both are popular). And additionally, if we provide transformation on the toJSON, it would stand to reason that they should be reconstituted when receiving them from the data store later. But it's not ideal to look for any date-like string and automatically transform it into a Date object.

We could manage this with a config setting but it also seems less than ideal to start adding flags and settings. So in the end, it seems appropriate to leave this up to the implementation to decide by implementing $$added/$$updated and toJSON as appropriate.

katowulf avatar Aug 07 '14 22:08 katowulf

I understand the decision, but it makes a lot of work to save and retrieve a Date object, if it can't be stored natively.

When you are working with a ng-model, for example, having a date in the $scope means to check every time, if it's a String created by .toJSON() or if it's a native Date object. Because it could either be a newly created Date object bound to the $scope or it could have com from firebase.

So in my opinion there should be a standardized way of how to store and work with Date objects in Firebase (and angularfire).

richardbrammer avatar Aug 11 '14 20:08 richardbrammer

Thanks for the feedback @richardbrammer. Great stuff. It's fortunately not much work. Just utilize the decorators.

app.config(function($provide) {
    $provide.decorator('$firebaseUtils', function($delegate) {
        var _updateRecord = $firebaseUtils.updateRecord;
        $firebaseUtils.updateRecord = function(rec, snap) {
             _updateRecord(rec, snap);
             $firebaseUtils.each(rec, function(v,k) {
                 if( k === 'date' ) { rec[k] = new Date(v); }
              });
        };

        var _toJSON = $firebaseUtils.toJSON;
        $firebaseUtils.toJSON = function(data) {
             var dataCopy = angular.extend({}, data);
            if( dataCopy.date ) { dataCopy.date = dataCopy.date.valueOf(); }
            return _toJSON(dataCopy);
        };
        return $delegate;
    });
});

katowulf avatar Aug 11 '14 20:08 katowulf

I guess my additional thoughts are that it would be nice if AngularFire worked similarly to $http, which converts dates using the toJSON method that is part of every Date object. You don't need to convert them back to Date objects when they come from the data store, as angular can take either a Date object or a JSON date string in almost all places. ($http doesn't re-initialize them).

As it is, every user of AngularFire (that uses dates) is going to have to find this thread and decorate the toJSON method. Seems like most users are going to need this functionality.

joshbowdoin avatar Aug 11 '14 20:08 joshbowdoin

If anything this is really a Firebase API issue as opposed to AngularFire. I'm curious why this is true:

var r = new Firebase('...');
var Ctor = function () {};
Ctor.prototype.toJSON = function () {
  return 'foo';
};
r.child('i').set(new Ctor(), function () {
  // {i: 'foo'}
});
r.child('d').set(new Date(), function () {
  // d is null
});

bendrucker avatar Aug 12 '14 11:08 bendrucker

@bendrucker - So I told @mikelehen about this and he looked into it. There does appear to be some bugginess here. He actually expected both to be null as we unofficially don't support these cases and was surprised that your first example works. We are looking into what to do here and are a bit surprised this hasn't come up before. I'll keep you posted on any updates, but those will happen tangentially to AngularFire.

jwngr avatar Aug 18 '14 23:08 jwngr

Got it. After some quick poking through the debug version it does look like JSON.stringify is used when available. The closure version would be used in IE 7 assuming it's still supported which would definitely result in different behavior. You'd have to not use JSON.stringify ever for the first case to not work. Very odd.

bendrucker avatar Aug 19 '14 11:08 bendrucker

Just a note for anyone who finds this while trying to sort out dates not saving to firebase, katowulf's snippet no longer works in 1.0.0, trying to decorate the firebaseUtils results in a circular reference error.

The theory is still sound with firebaseObject and overriding the $save and $$updated methods. Your answer will be found over here: https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-extending-the-services-decorating-the-services

ricketyboo avatar Mar 22 '15 05:03 ricketyboo

@rcuddy : thanks for that update, it's exactly what I'm looking for. However, being new to Firebase, I don't know where to apply this code. Do you know of a good resource with a better explanation?

minervadreaming avatar Mar 26 '15 06:03 minervadreaming

There is an example of using the extend methods and working with dates in the API.

katowulf avatar Mar 26 '15 14:03 katowulf

Hi @katowulf. Thanks, I did find the example in the APIs in the "Decorating the Services" section. However, being quite new and after having tried to insert said code into the places that I thought were logical (and failing), I was hoping for something a little more illustrative.

minervadreaming avatar Mar 26 '15 16:03 minervadreaming

Yeah, I'm really not sure what I can add to this example. I just don't understand what's left to illustrate. I'm happy to help, but you're going to have to a) start a new issue as this is a closed thread from over a year ago and b) illustrate the problem and where you're having trouble with the example.

// an object to return in our WidgetFactory
app.factory("Widget", function($firebaseUtils) {
  function Widget(snapshot) {
    // store the record id so AngularFire can identify it
    this.$id = snapshot.key();

    // apply the data
    this.update(snapshot);
  }

  Widget.prototype = {
    update: function(snapshot) {
      var oldData = angular.extend({}, this.data);

      // apply changes to this.data instead of directly on `this`
      this.data = snapshot.val();

      // add a parsed date to our widget
      this._date = new Date(this.data.date);

      // determine if anything changed, note that angular.equals will not check
      // $value or $priority (since it excludes anything that starts with $)
      // so be careful when using angular.equals()
      return !angular.equals(this.data, oldData);
    },

    getDate: function() {
      return this._date;
    },

    toJSON: function() {
      // since we changed where our data is stored, we need to tell AngularFire how
      // to get the JSON version of it. We can use $firebaseUtils.toJSON() to remove
      // private variables, copy the data into a shippable format, and do validation
      return $firebaseUtils.toJSON(this.data);
    }
  };

  return Widget;
});

// now let's create a synchronized array factory that uses our Widget
app.factory("WidgetFactory", function($firebaseArray, Widget) {
  return $firebaseArray.$extend({
    // change the added behavior to return Widget objects
    $$added: function(snap) {
      // instead of creating the default POJO (plain old JavaScript object)
      // we will return an instance of the Widget class each time a child_added
      // event is received from the server
      return new Widget(snap);
    },

    // override the update behavior to call Widget.update()
    $$updated: function(snap) {
      // we need to return true/false here or $watch listeners will not get triggered
      // luckily, our Widget.prototype.update() method already returns a boolean if
      // anything has changed
      return this.$getRecord(snap.key()).update(snap);
    }
  });
});

katowulf avatar Mar 26 '15 16:03 katowulf

Also found this old fiddle I wrote that demonstrates date manipulations using $extend. Updated it to 1.0.0. code base. Should be helpful as a simplified example.

http://jsfiddle.net/katowulf/syuzw9k1/

katowulf avatar Mar 26 '15 17:03 katowulf

@katowulf : Very helpful indeed. Thank you for taking the time!

minervadreaming avatar Mar 26 '15 17:03 minervadreaming