Timi Ajiboye

A Simple (Response) Service

Services in Sails.js are pretty easy to understand. They're simply JavaScript objects with functions that can be used everywhere (controllers, policies ... etc).

Services live in the /api/services folder.

To illustrate this, we'll look at a ResponseService I found lurking in my friend's code.

What this service's function does is to sort of format your API's request responses into this neat structure below:

{
  "response": {
    "message": "User created successfully",
    "data": {
      "user": {
        "id": 8
      }
    }
   "meta":{
      ... // meta stuff
   }
  }
}

Personally, I like the way the response is arranged into message, data and meta, so this is one service I see myself using pretty much every time my API is responding to a request.

/**
 * ResponseService.js
 */

module.exports = {  
    json: function (status, res, message, data, meta) {
        var response = {
            response: {
                message: message
            }
        };
        if (typeof data !== 'undefined') {
            response.response.data = data;
        }
        if (typeof meta !== 'undefined') {
            response.response.meta = meta;
        }
        return res.status(status).json(response);
    }
};

As we can see above, ResponseService has one method; json that takes five arguments.

  • status: the status code, i.e 200, 400 ...
  • res: the response object. This is always passed as an argument in to all action functions. It's the object one uses (prior to ResponseService) to respond to requests with JSON.
  • message: a simple message that helps to describe the overall nature of the response.
  • data: an object containing the actual data one would like to respond with. In the above scenario, I passed in a user object.
  • meta: well..an object with meta data, like number of pages or whatever.

To use this service, you simply call it's function as such:

User.create(data).then(function (user) {  
  return ResponseService.json(200, res, "User created successfully", user)
})

There you have it.
O dabọ.