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?