Upon updating, how to compare a model instance wit

2019-08-09 13:30发布

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?

2条回答
Ridiculous、
2楼-- · 2019-08-09 14:20

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

查看更多
我只想做你的唯一
3楼-- · 2019-08-09 14:25

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.

查看更多
登录 后发表回答