我想在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.
更多推荐
发布评论