I am looking to execute a separate function, like a Service function, before Sails renders the page into HTML. Please refer to the controller code below...
var MYController = {
index: function(req, res, next) {
req.flash("error", "Testing hello world");
MyCustomServices.myFunction( req, res );
res.view();
}
}
To include my service function, check api/services/MyCustomServices.js
exports.myFunction = function( req, res ){
Test.findOne({ code : "CODE" }, function(err, resp) {
if ( resp ) {
res.locals.TEST = resp;
}
});
var msg = req.flash('error');
res.locals.ERROR = msg.length>0 ? msg : "" ;
};
In this case, there is an additional process that needs to run before res.view() when calling MyCustomServices.myFunction( req, res );
The issue is that every time I call the res.view() function, I have to add this line in all my controller actions.
I attempted to add MyCustomServices.myFunction( req, res ); in express.js, but it didn't work as expected. It seems like it should be in express, but I'm not sure what codes are needed to be added.
The tasks performed by MyCustomServices.myFunction( req, res ) include:
- Fetching data from MongoDB using a query to Sails.
- Parsing req.flash messages to pass them to views for display.
Does anyone have ideas on how to resolve this?