Question

I'm new to Sails and I'm trying to figure out the best/proper method for returning a standard object for every API response.

The container our front-end requires is:

{
    "success": true/false,
    "session": true/false,
    "errors": [],
    "payload": []
}

Currently, I’m overwriting the blueprint actions in each controller like this example (which just seems so very, very wrong):

   find : function( req, res ){

    var id = req.param( 'id' );

    Foo.findOne( { id : id } ).exec( function( err, aFoo ){

      res.json(
        AppSvc.jsonReply(
          req,
          [],
          aFoo
        ), 200
      );
    });

  }

And in AppSvc.js:

  jsonReply : function( req, errors, data ){

    return {
      success : ( errors && errors.length ? false : true ),
      session : ( req.session.authenticated === true ),
      errors  : ( errors && errors.length ? errors : [] ),
      payload : ( data ? data : [] )
    };

  }

Additionally, I’ve had to modify each res.json() method for each default response (badRequest, notFound,etc). Again, this feels so wrong.

So, how do I properly funnel all API responses into a standard container?

Was it helpful?

Solution

Sails custom responses are great for this.

If you look at the blueprint code, you'll see that each one calls res.ok when it's done: https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/actions/find.js#L63

You can add your own file - ok.js - to api/responses/ - which will override the default built in handler.

https://github.com/balderdashy/sails/blob/master/lib/hooks/responses/defaults/ok.js <- just copy and paste this to start, and adapt as you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top