Restify:接下来“覆盖”默认值(Restify: “override” default next)

编程入门 行业动态 更新时间:2024-10-27 22:31:35
Restify:接下来“覆盖”默认值(Restify: “override” default next)

我想在Restify中覆盖默认值。 例如,现在我的代码就像

server.post('/names', function (req, res, next) { names = req.params.names; if (!Array.isArray(names)) { return next(new restify.errors.BadRequestError('names field is wrong or missing')); } res.send({ code: "OK" }); return next(); });

我希望它只是

server.post('/names', function (req, res, next) { names = req.params.names; if (!Array.isArray(names)) { return next(new restify.errors.BadRequestError('names field is wrong or missing')); } // Add names to DB return next(); });

next (对于非错误结果)是这样的

function next(res) { if (!body.hasOwnProperty("code")) { body["code"] = "OK"; } res.send(body); }

实现这个的最佳方法是什么?

I want to kinda override default next in Restify. E.g. now i have code like

server.post('/names', function (req, res, next) { names = req.params.names; if (!Array.isArray(names)) { return next(new restify.errors.BadRequestError('names field is wrong or missing')); } res.send({ code: "OK" }); return next(); });

I want it to be just

server.post('/names', function (req, res, next) { names = req.params.names; if (!Array.isArray(names)) { return next(new restify.errors.BadRequestError('names field is wrong or missing')); } // Add names to DB return next(); });

Where next (for non-error results) is like

function next(res) { if (!body.hasOwnProperty("code")) { body["code"] = "OK"; } res.send(body); }

What is the best way to implement this?

最满意答案

我想你可能正在寻找一个在链中的所有其他处理程序完成后执行的处理程序。 考虑“after”事件处理程序。 在文档中,它们显示了审计日志记录的示例 。

您应该能够使用相同的东西来根据需要更新响应主体。 代码可能看起来像这样......

server.on('after', function (request, response, route, error) {});

请记住,这仍然需要你return next(); 来自链中的所有其他处理程序。

I think you may be looking for a handler that executes after all other handlers in the chain are done. Consider the "after" event handler. In the documentation they show an example for audit logging.

You should be able to use that same thing to update the response body as needed. The code might look something like this...

server.on('after', function (request, response, route, error) {});

Keep in mind, this still requires you to return next(); from all of the other handlers in the chain.

更多推荐

本文发布于:2023-08-05 00:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1424162.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   Restify   default   override

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!