Joss
Joss

Reputation: 555

Cannot access to res variable on a Sails service

Based on (Sails documentation)[http://sailsjs.org/documentation/concepts/services/creating-a-service], I can create a service inside services folder doing this:

// EmailService.js - in api/services
module.exports = {

    sendInviteEmail: function(options) {

        var opts = {"type":"messages","call":"send","message":
            {
                "subject": "YourIn!",
                "from_email": "[email protected]",
                "from_name": "AmazingStartupApp",
                "to":[
                    {"email": options.email, "name": options.name}
                ],
                "text": "Dear "+options.name+",\nYou're in the Beta! Click <insert link> to verify your account"
            }
        };

        myEmailSendingLibrary.send(opts);

    }
};

So options recieve the params from the controller, but I don't know why this should work because myEmailSendingLibrary is not defined at all.

Also, I want to implement a find method with the ORM (waterline) inside a service. Based on Sails docs, must be something like:

 User.find({name:'Finn'}).exec(function (err, usersNamedFinn){
  if (err) {
    return res.negotiate(err);
  }
  sails.log('Wow, there are %d users named Finn.  Check it out:', usersNamedFinn.length, usersNamedFinn);
  return res.json(usersNamedFinn);
});

The problem comes when I try to join all. If I create the following service called DesignerService.js:

module.exports = {
  findFormIds: function(id) {
    Designer.find("56dedc1734112e8c1fb078aa").exec(function (err, records) {
    //}).exec(function (err, finn){
      if (err) {
        return res.negotiate(err);
      }
      if (!records) {
        return res.notFound('Could not find any form.');
      }

      //sails.log('Found "%s"', records.fullName);
      myFindFormIds.json(records);
      //return res.json(records);
    });
  }
};

This won't work because res is not created. If I try to declare a function in order to get access to res variable like this:

module.exports = function(req,res){
  findFormIds: function(id) {
    Designer.find("56dedc1734112e8c1fb078aa").exec(function (err, records) {
    //}).exec(function (err, finn){
      if (err) {
        return res.negotiate(err);
      }
      if (!records) {
        return res.notFound('Could not find any form.');
      }

      //sails.log('Found "%s"', records.fullName);
      myFindFormIds.json(records);
      //return res.json(records);
    });
  }
};

I have an error about unexpected ( in the findFormIds line.

So how could I access to res var in order to send back the results of the query?

Thanks!!

Upvotes: 1

Views: 875

Answers (1)

vkstack
vkstack

Reputation: 1644

First of All, you should perform operations on request and response always in your controllers.Though you can pass the response as a parameter to a service and do things whatever you want there. But i prefer the first way. you can use services like this.

your service

//   ./api/services/mySpecialService.js
module.exports={
  //this returns prime first number having last digit ==lastDigitOfPrimeNumber
  giveMePrimeNumber:function(lastDigitOfPrimeNumber){
    if(lastDigitOfPrimeNumber===1)
      return 11;
    else if(lastDigitOfPrimeNumber===3)
      return 3;
    else if(lastDigitOfPrimeNumber===5)
      return 5;
    else if(lastDigitOfPrimeNumber===7)
      return 7;
    else if(lastDigitOfPrimeNumber===9)
      return 19;
    else
      return "no such a prime number";
  },

  giveListOfPeople:function(query_name){
    var deferred=sails.q.defer();
    User.find({name:query_name}).exec(function(err,results){
      if(err)
        deferred.reject(err.message);
      else
        deferred.resolve(results)
    });
    return deferred.promise;
  },

};

your controller

//  ./api/controller/UserController.js
module.exports={
  getMePrimeWithGivenLastDigit:function(req,res){
    //if you send name in request body(post request).
    var lastDig=req.body.lastDigit;
    var ansJSON={
      "primeNumber":mySpecialService.giveMePrimeNumber(lastDig)
    };
    res.ok(ansJSON);
  },

  searchByName:function(req,res){
    //if you send name in request body(post request).
    var name=req.body.name;
    mySpecialService.giveListOfPeople(name)
      .then(function(resolvedResult){
        res.ok(resolvedResult);
      },function(failureReason){
        res.negotiate(failureReason);
      })
  }
};

i assume in your config/bootstrap.js u have added sails.q=require('q'); after installing q

(npm install q --save)

In the above service and controllers code i have used services with promises and without promises. About q-promise https://www.npmjs.com/package/q

Upvotes: 1

Related Questions