gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:47:15 26 4
gpt4 key购买 nike

我正在写一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com