Upon updating, how to compare a model instance with its former state

霸气de小男生 提交于 2019-12-11 07:51:46

问题


I'm using Sails.js v0.10.5, but this probably applies to more general MVC lifecycle logics (Ruby on Rails?).

I have two models, say Foo and Baz, linked with a one-to-one association. Each time that data in a Foo instance changes, some heavy operations must be carried out on a Baz model instance, like the costlyRoutinemethod shown below.

// api/model/Foo.js

module.exports {
  attributes: {
    name: 'string',
    data: 'json',
    baz: {
      model: 'Baz'
    }
  },

  updateBaz: function(criteria,cb) {
    Foo.findOne( criteria, function(err,foo) {
      Baz.findOne( foo.baz, function(err,baz) {
        baz.data = costlyRoutine( foo.data ); // or whatever
        cb();
      });
    });
  }
}

Upon updating an instance of Foo, it therefore makes sense to first test whether data has changed from old object to new. It could be that just name needs to be updated, in which case I'd like to avoid the heavy computation.

When is it best to make that check?

I'm thinking of the beforeUpdate callback, but it will require calling something like Foo.findOne(criteria) to retrieve the current data object. Inefficient? Sub-optimal?


回答1:


The only optimization I could think of:

You could call costlyRoutine iff relevant fields are being updated.

Apart from that, you could try to cache Foo (using some locality of reference caching, like paging). But that depends on your use case.

Perfect optimization would be really like trying to look into the future :D




回答2:


You might save a little by using the afterUpdate callback, which would have the Foo object already loaded so you can save a call.

// api/model/Foo.js

module.exports {
  attributes: {
    ...
  },

  afterUpdate: function(foo,cb) {
    Baz.findOne( foo.baz, function(err,baz) {
      baz.data = costlyRoutine( foo.data ); // or whatever
      cb();
    });
  }
}

Otherwise as myusuf aswered, if you only need to update based on relevant fields, then you can tap into it in the beforeUpdate callback.

Btw, instance functions should be defined inside attributes prop, lifecycle callbacks outside.



来源:https://stackoverflow.com/questions/27190939/upon-updating-how-to-compare-a-model-instance-with-its-former-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!