新的 NestJS Swagger 生成器
OpenAPI (Swagger) 文档生成器在 NestJS 中有了新的进化。
@nestia/sdk
自动分析 NestJS 源代码,在编译级别生成 OpenAPI 文档,无需像 @nestjs/swagger
装饰器函数调用那样额外操作。所有过程都由 @nestia/sdk
自动完成。
让我们设置 @nestia/sdk
,并利用它的优势吧。
- Github 仓库: https://github.com/samchon/nestia
- 使用文档: https://nestia.io/docs/sdk/swagger/#runtime-composition
DTO Schema
请看下面的 DTO(数据传输对象)模式示例,分别用于 @nestia/sdk
和 @nestjs/swagger
。哪一种更方便?如你所见,@nestia/sdk
只需纯 TypeScript 类型。而 @nestjs/swagger
需要在 DTO 模式中进行三重重复的类型定义。
考虑到安全性,@nestia/sdk
更加有用。由于 @nestjs/swagger
在 DTO 模式中的三重重复定义,生产力和可维护性降低,容易导致用户犯错。更糟糕的是,如果你错误使用了 @nestjs/swagger
装饰器,即使它们与实际的 TypeScript 类型不同,也不会出现编译错误。此外,@nestia/sdk
只需要纯 TypeScript 类型,因此不会出现类似 @nestjs/swagger
的问题。
这就是你应该在 NestJS 中使用 @nestia/sdk
进行 OpenAPI 生成的原因。@nestia/sdk
将分析你的 TypeScript DTO 类型,在编译级别自动生成 OpenAPI 规范的 JSON 模式。使用它可以同时提升生产力、可维护性和安全性。
软件开发工具包
左侧是 NestJS 服务器代码,右侧是利用 SDK 的客户端代码。
如果你设置了 @nestia/sdk
,不仅可以生成 OpenAPI (Swagger) 文档,还可以为客户端开发者生成 SDK (软件开发工具包) 库,包含严格类型定义的 fetch()
函数。
如上图右侧所示,客户端程序员可以通过 SDK 库非常方便且安全地开发 API 交互程序。这个 SDK 库也是通过 @nestia/sdk
分析编译级别的 TypeScript 源代码生成的。
如果你成功生成了 OpenAPI 文档,接下来可以挑战生成 SDK (软件开发工具包) 库。
Swagger-UI + TypeScript 编辑器
如果你成功构建了 OpenAPI (Swagger) 文档,可以通过 Swagger-UI 提供给合作开发者。此外,如何将 Swagger-UI 与嵌入 SDK (软件开发工具包) 库的在线 TypeScript 编辑器结合起来呢?
只需访问上述网站 ( https://nestia.io/docs/editor/) 并将 Swagger 文件放入其中。然后,在线 TypeScript 编辑器 (StackBlitz) 将与 Swagger-UI 结合打开,客户端开发者可以更高效地使用它。