如何将每个 API 响应包装到 SailsJS 中的标准回复对象中? [英] How can I wrap each API response into a standard reply object in SailsJS?
问题描述
我是 Sails 的新手,我正在尝试找出为每个 API 响应返回标准对象的最佳/正确方法.
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
);
});
}
在 AppSvc.js 中:
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 : [] )
};
}
此外,我不得不为每个默认响应(badRequest、notFound 等)修改每个 res.json()
方法.再次,这感觉很不对.
Additionally, I’ve had to modify each res.json()
method for each default response (badRequest, notFound,etc). Again, this feels so wrong.
那么,如何将所有 API 响应正确地汇集到标准容器中?
So, how do I properly funnel all API responses into a standard container?
推荐答案
Sails 自定义响应对此非常有用.
Sails custom responses are great for this.
如果您查看蓝图代码,您会看到每个完成后都调用 res.ok:https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/actions/find.js#L63
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
您可以将自己的文件 - ok.js - 添加到 api/responses/- 这将覆盖默认的内置处理程序.
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 <- 只需复制并粘贴即可开始,并根据需要进行调整.
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.
这篇关于如何将每个 API 响应包装到 SailsJS 中的标准回复对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!