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 costlyRoutine
method 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?
The only optimization I could think of:
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
You might save a little by using the
afterUpdate
callback, which would have theFoo
object already loaded so you can save a call.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.