Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wrap each API response into a standard reply object in SailsJS?

Tags:

sails.js

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?

like image 273
NotJustClarkKent Avatar asked May 07 '14 21:05

NotJustClarkKent


1 Answers

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.

like image 161
Rob Wormald Avatar answered Sep 24 '22 09:09

Rob Wormald