恢复:"override"默认下一个
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);
}
实现这个的最佳方法是什么?
我想您可能正在寻找一个在链中所有其他处理程序完成后执行的处理程序。考虑 "after" 事件处理程序。在文档中,他们显示 an example for audit logging.
您应该能够根据需要使用相同的东西来更新响应正文。代码可能看起来像这样...
server.on('after', function (request, response, route, error) {});
请记住,这仍然需要您从链中的所有其他处理程序中 return 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);
}
实现这个的最佳方法是什么?
我想您可能正在寻找一个在链中所有其他处理程序完成后执行的处理程序。考虑 "after" 事件处理程序。在文档中,他们显示 an example for audit logging.
您应该能够根据需要使用相同的东西来更新响应正文。代码可能看起来像这样...
server.on('after', function (request, response, route, error) {});
请记住,这仍然需要您从链中的所有其他处理程序中 return next();
。