我有多个以/networks/{networkId}/*
开头的端点。我不希望在每个处理程序中都有逻辑来查找网络并对其执行一些额外的验证。有没有办法在更高的层次上解决这个问题?防爆。插件/服务器方法等?
在每个处理程序中,我都有以下样板代码:
import networkRepo from 'common/repositories/network';
// handler.js
export default (req, reply) => {
return networkRepo.findById(req.params.networkId).then(network => {
// Logic to validate whether the logged user belongs to the network
// Logic where I need the network instance
});
}
最好的情况是:
// handler.js
export default (req, reply) => {
console.log(req.network); // This should be the network instance
}
答案 0 :(得分:0)
实现您想要的最佳方法是创建一个可以在处理程序中首先调用的泛型函数,或者创建一个内部hapi路径,它将执行查找并将值返回给其他处理程序。然后,server.inject可以从您的其他处理程序访问内部路由,请参阅名为allowInternals的选项以获取更多详细信息,我可以编写伪代码来帮助您!
[{
method: 'GET',
path: '/getNetworkByID/{id}',
config: {
isInternal: true,
handler: function (request, reply) {
return networkRepo.findById(req.params.networkId).then(network => {
// Logic to validate whether the logged user belongs to the network
// Logic where I need the network instance
reply(network.network);
});
}
}
},
{
method: 'GET',
path: '/api/networks/{id}',
config: {
isInternal: true,
handler: function (request, reply) {
request.server.inject({
method: 'GET',
url: '/getNetworkByID/' + request.params.id,
allowInternals: true
}, (res) => {
console.log(res.result.network) //network
});
}
}
}]