Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get req and res in a Sailsjs service?

Tags:

sails.js

I've recently started using services in sailsjs to cut down on code in my controllers. Heres's an example of how I call a function in my service:

ValidationService.addError(req,res,'Password is too short.'); 

Notice I pass req and res to my service. Why arent these already available? How can I add them to the service so I dont always have to explicitly pass them?

As requested, here is the code in my service:

var errorCss = 'alert-danger';
var successCss = 'alert-success';

module.exports = {

init : function(req,res){

    req.session.flash = {};
    req.session.flash.alert = {};
    req.session.flash.alert.data = [];
    req.session.flash.alert.result = 'pass';

},

addError : function(req,res,error){
    req.session.flash.alert.data.push(error);
    req.session.flash.alert.css = errorCss;
    req.session.flash.alert.result = 'fail';
},

addSuccess: function(req,res,success){
    req.session.flash.alert.data.push(success);
    req.session.flash.alert.css = successCss;
},  

isValid : function(req,res){

    if ((req.session.flash.alert.result == 'pass')){
        return true;
    }

    return false;
},

clear : function(req,res){
    delete req.session.flash;
}

}
like image 851
Kory Avatar asked Dec 06 '25 14:12

Kory


1 Answers

I'm sure you read this already, but take another look at the definition of the Sails services. This, basically, means that you can have in your services any common code, not necessarily something dealing with request and response. For example, there can be a part of your application that you are running from the command line: there will be no request or response in this case, but you still want to be able to use your services.

Bottom line, you are doing it right already by passing req/res. (Just don't overdo it: you should only create services for the code you are using in multiple places, doing it for every controller doesn't make sense).

like image 190
bredikhin Avatar answered Dec 09 '25 16:12

bredikhin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!