Services

Overview

Services can be thought of as libraries which contain functions that you might want to use in many places of your application. For example, you might have an EmailService which wraps some default email message boilerplate code that you would want to use in many parts of your application. The main benefit of using services in Sails is that they are globalized—you don’t have to use require() to access them.

How do I create a service?

Simply save a Javascript file containing a function or object into your api/services folder. The filename will be used as the globally-accessible variable name for the service. For example, an email service might look something like this:

  1. // EmailService.js - in api/services
  2. module.exports = {
  3. sendInviteEmail: function(options) {
  4. var opts = {"type":"messages","call":"send","message":
  5. {
  6. "subject": "YourIn!",
  7. "from_email": "info@balderdash.co",
  8. "from_name": "AmazingStartupApp",
  9. "to":[
  10. {"email": options.email, "name": options.name}
  11. ],
  12. "text": "Dear "+options.name+",\nYou're in the Beta! Click <insert link> to verify your account"
  13. }
  14. };
  15. myEmailSendingLibrary.send(opts);
  16. }
  17. };

You can then use EmailService anywhere in your app:

  1. // Somewhere in a controller
  2. EmailService.sendInviteEmail({email: 'test@test.com', name: 'test'});