简体   繁体   中英

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. the HttpGet decorator creates a route with the path 'foo/:id' and foo as its only handler in ARouter.

i want the @validate decorator to add another handler (specific function middleware, will be called before foo) to the foo route handlers stack. eg like it was router.get('/foo/:id/, validationFunction, foo).

is there a way to dynamiclly add handler to the foo route in the router?

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)).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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