我已經實作了一個很好的中間件,它根據正則運算式檢查提供的查詢引數,如果沒有問題,它會呼叫 next(),如果有問題,它會呼叫 next(Error)。
export class ValidateRegistrationMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction){
let reg = new RegExp('^[A-Z0-9 _]*$');
if (reg.test(req.params.registration)) {
next()
} else {
next(new InvalidRegistrationException('Invalid Registration :' req.params.registration, HttpStatus.BAD_REQUEST));
}
}
}
我通過在模塊組件的類中設定配置來使其作業。
@Module({
controllers: [MyController],
providers: [MyService]
})
export class MyModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(ValidateRegistrationMiddleware).forRoutes({
path: 'service/:registration',
method: RequestMethod.GET
})
}}
這很好用,但我無法實作它并在我正在處理的控制器的單元測驗中使用它。在我的規范檔案中,我在 beforeEach 中設定了模塊,但我看不到在哪里設定中間件。它是在模塊類中設定的,而不是在我的實際模塊中的 @Decorator 中。
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [MyController],
providers: [MyService],
}).compile();
controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);
});
如何讓中間件在每次測驗之前運行?我想測驗一個無效的注冊,但目前中間件沒有被呼叫。
uj5u.com熱心網友回復:
在測驗模塊中,您參考了提供者和控制器,但是您的中間件設定存在于MyModule其中并沒有在任何地方指定。
如果您MyModule改為匯入,我相信您的中間件配置將初始化。
在下面試試這個
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [MyModule],
}).compile();
controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/432054.html
