Question

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;
}

}
Was it helpful?

Solution

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).

OTHER TIPS

other refactoring is in order...

I suppose you could make some kind of global, but that would make the app go completely haywire. As users might now be sharing sessions. If it didn't just blow up altogether.

But looking at your question, I see you are using a service to validate password length. You should be using the model for this. Take a look at Validations

In response to your comment....

Validations can be functions and can even depend on multiple fields too!

see below...

attributes: {
  website: {
    type: 'string',
    contains: function(cb) {
      setTimeout(function() {
        cb('http://');
      }, 1);
    }
  }

  startDate: {
    type: 'date',
    before: function() {
      return this.endDate;
    }
  },

  endDate: {
    type: 'date',
    after: function() {
      return this.startDate;
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top