2017-05-05 13 views
2

にハンドラを追加し、私は実際に、されることを意味私はこのコードを持っていると仮定しています何:dynamicly急行ルート機能

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ルートにdynamicllyハンドラを追加する方法はありますか?

ありがとうございます! decorators documentationに基づい

答えて

0

複数のデコレータは、単一の宣言に適用すると、それらの 評価は数学の組成物を機能と同様です。この モデルでは、関数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(); 
} 

(私はそれをテストしていないことに注意してください)

関連する問題