【问题标题】:How to install Express middleware (express-openapi-validator) in NestJS?如何在 NestJS 中安装 Express 中间件(express-openapi-validator)?
【发布时间】:2021-03-13 11:36:38
【问题描述】:

我正在编写一个NestJS 应用程序。现在我要安装Express中间件express-openapi-validator

但是,我无法让它工作。有description for how to install the express-openapi-validator in express,但是总是会报错。

例如

export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        consumer.apply(middleware({apiSpec "./bff-api.yaml"}))
            .forRoutes(OrganizationController)
    }
}

结果

error TS2345: Argument of type 'OpenApiRequestHandler[]' is not assignable to parameter of type 'Function | Type<any>'.
      Type 'OpenApiRequestHandler[]' is missing the following properties from type 'Type<any>': apply, call, bind, prototype, and 4 more.

如何在 NestJS 中安装这个中间件?

【问题讨论】:

    标签: express validation nestjs middleware openapi


    【解决方案1】:

    我现在已经开始工作了:

    configure(consumer: MiddlewareConsumer) {
        middleware({
            apiSpec: `${__dirname}/../api-doc/bff-api.yaml`
        }).forEach(value => consumer.apply(value).forRoutes(OrganizationController))
    }
    

    【讨论】:

      【解决方案2】:

      我在 express-openapi-validator (static link for posterity) 中添加了 NestJS example

      AppModule 看起来基本相同,尽管您不需要遍历中间件:

      @Module({
        imports: [PingModule],
        providers: [{ provide: APP_FILTER, useClass: OpenApiExceptionFilter }],
      })
      export class AppModule implements NestModule {
        configure(consumer: MiddlewareConsumer) {
          consumer
            .apply(
              ...OpenApiValidator.middleware({
                apiSpec: join(__dirname, './api.yaml'),
              }),
            )
            .forRoutes('*');
        }
      }
      

      我还添加了一个异常过滤器,将错误从express-openapi-validator 转换为正确的响应;否则我总是会收到 500 错误。您也可以使用这种方法将错误转换为自定义错误格式。

      import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
      import { Response } from 'express';
      import { error } from 'express-openapi-validator';
      
      @Catch(...Object.values(error))
      export class OpenApiExceptionFilter implements ExceptionFilter {
        catch(error: ValidationError, host: ArgumentsHost) {
          const ctx = host.switchToHttp();
          const response = ctx.getResponse<Response>();
      
          response.status(error.status).json(error);
        }
      }
      
      interface ValidationError {
        status: number;
        message: string;
        errors: Array<{
          path: string;
          message: string;
          error_code?: string;
        }>;
        path?: string;
        name: string;
      }
      

      【讨论】:

        猜你喜欢
        • 2023-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-24
        • 2017-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多