繁体   English   中英

如何在 Nx monorepo 中为 NestJS 和 Angular 之间共享的 API 接口启用 Swagger?

[英]How to enable Swagger for API interfaces shared between NestJS and Angular within Nx monorepo?

我想为 API 接口启用 Swagger,在 Nx monorepo 中的 NestJS 和 Angular 应用程序之间共享。 是否有一致且不具有解决方法的方法?

这些是我没有成功的方法:

方法 1. 将@nestjs/swagger装饰器应用于共享 DTO 类

  • 使用 npx npx create-nx-workspace@latest创建一个新的 Nx monorepo
  • select angular-nest工作区蓝图
  • 安装 Swagger 依赖项并根据指南引导它
  • app.component.ts中添加Message类型的输入(没有意义,仅用于测试):
export class AppComponent {
  @Input() message: Message;

  hello$ = this.http.get<Message>('/api/hello');
  constructor(private http: HttpClient) {}
}
  • api-interfaces.ts中使用ApiProperty()装饰message属性:
import { ApiProperty } from '@nestjs/swagger';

export class Message {
  @ApiProperty()
  message: string;
}
  • 运行 NestJS 应用程序。 它工作正常,Swagger 在 Web 视图中显示正确的 DTO 结构
  • 但是,当我启动 Angular 应用程序时,出现错误:
WARNING in ./node_modules/@nestjs/common/utils/load-package.util.js 8:39-59
Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/express/lib/view.js 81:13-25
Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/@nestjs/mapped-types/dist/type-helpers.utils.js
Module not found: Error: Can't resolve 'class-transformer' in '.\node_modules\@nestjs\mapped-types\dist'

ERROR in ./node_modules/@nestjs/common/cache/cache.providers.js
Module not found: Error: Can't resolve 'cache-manager' in '.\node_modules\@nestjs\common\cache'
ERROR in ./node_modules/@nestjs/common/pipes/validation.pipe.js
Module not found: Error: Can't resolve 'class-transformer' in '.\node_modules\@nestjs\common\pipes'
...

这看起来像一个捆绑问题,类似于这个 在 Angular 版本中,我还没有找到任何优雅的工作解决方案来修复它。

方法 2. 使用NestJS Swagger 插件并避免使用装饰器

这将是比前一个更好的方法,但它没有工作。 首先,Swagger 插件需要 NestJS CLI,而在 Nx monorepo 中则不然。 有一个问题建议一些解决方法,但我还没有发现它们足够可靠和完整。 其次,该插件没有涵盖一些重要的用例,这些用例仍然需要装饰器。 例如:

@ApiProperty({
  oneOf: [{ $ref: getSchemaPath(TypeA) }, { $ref: getSchemaPath(TypeB) }],
})
type: TypeA | TypeB;

如上所述,装饰器会导致错误。

方法 3. 从 DTO 类中创建接口以供 Angular 应用程序专用

这种方法吸引我的是能够从后端特定逻辑中抽象出来,无论是 Swagger、序列化还是验证装饰器。 我们可以做到以下几点:

// Expose to the back-end
export class MessageDto {
  @ApiProperty()
  message: string;
}

// Expose to the front-end
export interface Message extends MessageDto {}

在这种情况下,使用 Angular 应用程序可以很好地编译Message接口。 但是一旦我们引入更复杂的 DTO 组合(具有嵌套 DTO 的类),这种方法就不起作用了。

我将不胜感激任何其他想法。

我已成功在 Angular 和 Nest.js 之间共享 DTO(方法 #1)

@angular-devkit/build-angular:browser替换为@angular-builders/custom-webpack:browser已解决构建或提供 angular 应用程序时的错误。

有关详细信息,请参阅https://github.com/nestjs/nest/issues/1706#issuecomment-474657479

作为简单的解决方法,您可以使用 ApiModelProperty 装饰器而不是 ApiProperty:

import { ApiModelProperty } from '@nestjs/swagger/dist/decorators/api-model-property.decorator';

ApiModelProperty 不会导致缓存管理器注入问题,并且装饰器将允许您为 DTO 设置 API 文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM