For experts familiar with sails.js: I have a Customers Model and to keep it simple lets say
/**
* Customers.js
*/
module.exports = {
attributes: {
firstName: { type: 'string' },
lastName: { type: 'string' }
}
};
IMPORTANT: There is also a CustomerHistory Model as shown below. Whenever a Customer is created or updated, a corresponding CustomerHistory record should also be inserted/created.
/**
* CustomerHistory.js
*/
module.exports = {
attributes: {
customer: { model: 'customer' },
firstName: { type: 'string' },
lastName: { type: 'string' },
modifiedAt: { type: 'datetime'}
}
};
OPTIONS within Sails.js:
Override or Create new Sails Blueprint actions (let's call it CreateWithHistory and UpdateWithHistory) which always inserts into CustomerHistory upon successful save into Customer. If this is the proposed solution, a code sample would help.
Create custom controller actions (let's call it CreateWithHistory and UpdateWithHistory) which always inserts into CustomerHistory upon successful save into Customer. If this is the proposed solution, a code sample would help as to how to chain 2 Model.create and Model.update with Model.create actions.
Create a custom Customers Model action to implicitly save into history on create or update. How to do this?
Sails js provides lifecycle callbacks for models you can use. They allow you to execute custom code whenever new models are created, updated, or at other times. I think you can accomplish what you want by adding callbacks to your Customer
model. In Customer.js
:
module.exports = {
attributes: {
firstName: { type: 'string' },
lastName: { type: 'string' }
},
// this will create a new CustomerHistory for each Customer created
afterCreate: function(customer, cb) {
CustomerHistory.create({
customer: customer.id,
firstName: customer.firstName,
lastName: customer.lastName,
modifiedAt: new Date()
}).exec(function(err, history) {
if (err) { return cb(err); }
cb();
});
},
// update some fields in CustomerHistory after Customer is updated
afterUpdate: function(customer, cb) {
CustomerHistory.update({customer: customer.id}, {
firstName: customer.firstName,
lastName: customer.lastName,
modifiedAt: new Date()
}).exec(function(err, history) {
if (err) { return cb(err); }
cb();
});
}
};
This may not be the exact flow you want (for example, maybe you sometimes create the history first, sometimes don't modify the history on update, etc), but I think using the list of available callbacks should be able to accomplish what you want.