【问题标题】:Multiple methods for hapijs handlerhapijs 处理程序的多种方法
【发布时间】:2015-06-30 18:39:41
【问题描述】:

我使用过 express,您可以在其中传递多个方法以传递如下路线:

app.get('/users/,[
  validator.validate,
  controller.get
]);

然后每个函数使用 next() 回调将控制权传递给数组中的下一个函数。有没有可以在 hapijs 处理程序中完成的等效操作?我希望我的函数像 express 路由处理程序一样可重用和独立。

谢谢。

【问题讨论】:

    标签: node.js hapijs


    【解决方案1】:

    hapi 有Route Prerequisites,它允许您在实际处理程序本身之前运行一组类似处理程序的函数。如果您在配置本身之外定义它们,它们都是可重用且独立的。

    每个预获取中生成的值设置在request.pre 对象上,以便在您的处理程序中使用。这是一个例子:

    var step1 = function (request, reply) {
    
        reply('The quick brown fox ');
    };
    
    var step2 = function (request, reply) {
    
        reply('jumped over the lazy dog.');
    };
    
    server.route({
        config: {
            pre: [
                step1,
                step2
            ]
        },
        method: 'GET',
        path: '/',
        handler: function (request, reply) {
    
            var response = request.pre.step1 + request.pre.step2;
            reply(response);
        } 
    });
    

    默认情况下,每个 pre 将串联运行,类似于 async 包中的 async.series/waterfall 函数。如果你想让一组 pres 相互并行运行,只需将它们放在一个数组中,你就会得到类似async.parallel:

    server.route({
        ...
        config: {
            pre: [
                [ step1, step2 ], // these run together
                step3             // and then this one
            ]
        },
        ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多