作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在写一个 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/
我是一名优秀的程序员,十分优秀!