繁体   English   中英

动态将处理程序添加到快速路由功能

[英]dynamicly add handlers to an express route 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);
    }
}

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

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

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

谢谢!

根据装饰器文档

当多个修饰符应用于一个声明时,其求值类似于数学中的函数组成。 在这个模型中,当组合函数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();
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM