42

I have a question consisting of two parts:

  1. What are the types of services one would add to the api/services folder in a sails.js app.
  2. How would one 'wire' those services to the rest of the application.

Thanks,

TM

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
tmueller
  • 512
  • 1
  • 5
  • 8

1 Answers1

49

a service would be in my opinion, a piece of logic that you need in multiple locations of your app. for example an email service. the following is taken directly from the sails-wiki github page.

// EmailService.js - in api/services
exports.sendInviteEmail = function(options) {

var opts = {"type":"messages","call":"send","message":
    {
        "subject": "YourIn!",
        "from_email": "info@balderdash.co",
        "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);
};

The wiring is done by sails itself:

// Somewhere in a conroller
 EmailService.sendInviteEmail({email: 'test@test.com', name: 'test'});
M4rk
  • 2,172
  • 5
  • 36
  • 70
snyx
  • 1,104
  • 8
  • 8
  • how would I create a service that returns some JSON? – deiga Mar 01 '14 at 11:01
  • you can't bind a service to a route. you have to return a promise or hand over a callback and handle the rendering inside your controller – snyx Mar 01 '14 at 23:05
  • What do you mean with a promise? I currently made my service accept a callback function and let the controller handle the data through there – deiga Mar 02 '14 at 07:43
  • promises are just another way of handling your async calls. https://github.com/petkaantonov/bluebird#what-are-promises-and-why-should-i-use-them – snyx Mar 02 '14 at 11:31