简体   繁体   English

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

[英]dynamicly add handlers to an express route function

what i am actually mean is, assume i have this code: 我的实际意思是,假设我有以下代码:

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

what i have here is a router, decorators, and a foo function. 我在这里拥有的是路由器,装饰器和foo函数。 the HttpGet decorator creates a route with the path 'foo/:id' and foo as its only handler in ARouter. HttpGet装饰器创建一个路径为foo /:id且foo为ARouter中唯一处理程序的路由。

i want the @validate decorator to add another handler (specific function middleware, will be called before foo) to the foo route handlers stack. 我希望@validate装饰器将另一个处理程序(特定功能中间件,将在foo之前调用)添加到foo路由处理程序堆栈中。 eg like it was router.get('/foo/:id/, validationFunction, foo). 例如,就像是router.get('/ foo /:id /,validationFunction,foo)。

is there a way to dynamiclly add handler to the foo route in the router? 有没有办法在路由器的foo路由中动态添加处理程序?

Thanks! 谢谢!

Based on the decorators documentation : 根据装饰器文档

When multiple decorators apply to a single declaration, their evaluation is similar to function composition in mathematics. 当多个修饰符应用于一个声明时,其求值类似于数学中的函数组成。 In this model, when composing functions f and g, the resulting composite (f ∘ g)(x) is equivalent to f(g(x)). 在这个模型中,当组合函数f和g时,所得的合成(f∘g)(x)等于f(g(x))。

So you can do something like: 因此,您可以执行以下操作:

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

And change the order of your decorators: 并更改装饰器的顺序:

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

(keep in mind that I haven't tested it) (请记住,我还没有测试过)

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

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