【问题标题】:dynamicly add handlers to an express route function将处理程序动态添加到快速路由函数
【发布时间】:2017-05-06 02:40:48
【问题描述】:

我的意思是,假设我有这个代码:

var ARouter = Router();    

@Validate({
    params: {
        id: joi.number(),
        x: joi.number()
    }
})
@HttpGet('/foo/:id')
foo(req: Request, res: Response) {
    res.send('in foo').end();
}

function HttpGet(path: string) {
    return function (target: ApiController, propertyName: string, descriptor: TypedPropertyDescriptor<RequestHandler>) {
        ARouter.get(path, descriptor.value);
    }
}

我这里有一个路由器、装饰器和一个 foo 函数。 HttpGet 装饰器创建一个路径,路径为 'foo/:id' 和 foo 作为其在 ARouter 中的唯一处理程序。

我希望@validate 装饰器将另一个处理程序(特定函数中间件,将在 foo 之前调用)添加到 foo 路由处理程序堆栈。 例如就像是 router.get('/foo/:id/, validationFunction, foo)。

有没有办法在路由器的 foo 路由中动态添加处理程序?

谢谢!

【问题讨论】:

    标签: node.js express typescript


    【解决方案1】:

    基于decorators documentation:

    当多个装饰器应用于单个声明时,它们的 评估类似于数学中的函数组合。在这 模型,当组合函数 f 和 g 时,得到的复合 (f ∘ g)(x) 等价于 f(g(x))。

    所以你可以这样做:

    function validate(params: any, fn: (req: Request, res: Response) => void) {
        // validate data here and based on that decide what to do next
    }
    
    function Validate(params: any) {
        return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
            const newDescriptor = Object.assign({}, descriptor);
    
            newDescriptor.value = function(req: Request, res: Response) {
                validate(params, descriptor.value);
            }
    
            return newDescriptor;
        }
    }
    

    并更改装饰器的顺序:

    @HttpGet('/foo/:id')
    @Validate({
        params: {
            id: joi.number(),
            x: joi.number()
        }
    })
    foo(req: Request, res: Response) {
        res.send('in foo').end();
    }
    

    (请记住,我还没有测试过)

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 2016-10-10
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多