express - 如何在 NestJS 中安装 Express 中间件(express-openapi-validator)?

标签 express validation nestjs middleware openapi

我正在写一个 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 中安装这个中间件?

最佳答案

我添加了一个 NestJS example到 express-openapi-validator ( static link for posterity )。

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

关于express - 如何在 NestJS 中安装 Express 中间件(express-openapi-validator)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65092351/

相关文章:

node.js - 无法更新mongodb中的数据

node.js - 使用 bookshelf.js/knex.js[mysql] +express.js 获取最后一条记录 id

asp.net - 根据 DropDownList 选择验证 TextBox

php - Yii email 的验证器到底验证了什么?

node.js - 向nestjs swagger添加服务器出现权限错误

javascript - NestJs SSL : error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

node.js - 在 "request"中调用模块的本地函数作为回调

mysql - 自定义快速验证器

python - 服务器端表单验证和 POST 数据

javascript - 将属性添加到 Express 请求对象