dynamic地将处理程序添加到快速路由function

我实际上是什么意思是,假设我有这样的代码:

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

我在这里有一个路由器,装饰和一个富function。 HttpGet装饰器创build一条path为“foo /:id”的路由,foo作为其在ARouter中唯一的处理器。

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

有没有办法dynamic地添加处理程序到foo路由在路由器?

谢谢!

根据装饰者文档 :

当多个装饰者适用于一个声明时,其评价类似于math中的函数组合。 在这个模型中,当组合函数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(); } 

(请记住,我没有testing过)