2016-06-16 20 views
0

我有多个以/networks/{networkId}/*开头的端点。我不想在每个处理程序中寻找网络并对其执行一些额外的验证。有没有什么办法可以在更高层次上解决这个问题?防爆。插件/服务器方法等?HapiJS在处理程序中声明请求

在每一个处理程序,我有以下样板代码:

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

你为什么打电话给reply.continue()?此外,您的测试看起来不正确 –

+0

我修改了问题 – guidsen

+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 
      }); 

     } 
    } 
}] 
+0

您可以添加一些简单的伪代码,将对象从处理程序X传递到处理程序Y – guidsen

+0

希望这解释更好 –