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

a 夏天 提交于 2019-12-10 04:19:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23528352/how-can-i-wrap-each-api-response-into-a-standard-reply-object-in-sailsjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!