[英]How to enable Swagger for API interfaces shared between NestJS and Angular within Nx monorepo?
我想为 API 接口启用 Swagger,在 Nx monorepo 中的 NestJS 和 Angular 应用程序之间共享。 是否有一致且不具有解决方法的方法?
这些是我没有成功的方法:
@nestjs/swagger
装饰器应用于共享 DTO 类npx create-nx-workspace@latest
创建一个新的 Nx monorepoangular-nest
工作区蓝图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;
}
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 版本中,我还没有找到任何优雅的工作解决方案来修复它。
这将是比前一个更好的方法,但它没有工作。 首先,Swagger 插件需要 NestJS CLI,而在 Nx monorepo 中则不然。 有一个问题建议一些解决方法,但我还没有发现它们足够可靠和完整。 其次,该插件没有涵盖一些重要的用例,这些用例仍然需要装饰器。 例如:
@ApiProperty({
oneOf: [{ $ref: getSchemaPath(TypeA) }, { $ref: getSchemaPath(TypeB) }],
})
type: TypeA | TypeB;
如上所述,装饰器会导致错误。
这种方法吸引我的是能够从后端特定逻辑中抽象出来,无论是 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.