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

I am new to Sails and I am trying to find the best / right method to return a standard object for each API response.

The container that our interface requires:

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

Im currently overwriting the drawing actions in each controller, like this example (which just seems 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 : [] ) }; } 

In addition, Ive had to modify each res.json() method for each default answer (badRequest, notFound, etc.). Again, this seems so wrong.

So, how to correctly insert all API responses into a standard container?

+7
source share
1 answer

Sails custom answers are great for this.

If you look at the drawing code, you will see that everyone calls res.ok when it is done: https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/actions/find.js# L63

You can add your own file - ok.js - in api / answers / - 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 needed.

+6
source share

All Articles