新的 NestJS Swagger 生成器

import { NestiaSwaggerComposer } from "@nestia/sdk";
import { INestApplication } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { SwaggerModule } from "@nestjs/swagger";

const main = async (): Promise<void> => {
  const app: INestApplication = await NestFactory.create(ApplicationModule);
  const document = await NestiaSwaggerComposer.document(app, {
    openapi: "3.1",
    servers: [
      {
        url: "http://localhost:3000",
        description: "Localhost"
      }
    ]
  });
  SwaggerModule.setup("api", app, document as any);
  await app.listen(3_000);
};
main().catch(console.error);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

OpenAPI (Swagger) 文档生成器在 NestJS 中有了新的进化。

@nestia/sdk 自动分析 NestJS 源代码,在编译级别生成 OpenAPI 文档,无需像 @nestjs/swagger 装饰器函数调用那样额外操作。所有过程都由 @nestia/sdk 自动完成。

让我们设置 @nestia/sdk,并利用它的优势吧。

npx nestia setup --runtime
  • 1.

DTO Schema

//----
// 在 @nestia/sdk 中仅需使用接口类型
//----
export interface IBbsArticle {
  /**
   * 附件文件列表。
   */
  files: null | IAttachmentFile[];
}

//----
// 在 @nestjs/swagger 中需要重复定义
//----
export class BbsArticle {
  // 重复的模式定义
  // - 重复的函数调用 + 属性类型
  // - 必须自己指定 `isArray` 和 `nullable` 属性
  @ApiProperty({
    type: () => AttachmentFile,
    nullable: true,
    isArray: true,
    description: "附加文件列表。",
  })
  @Type(() => AttachmentFile)
  @IsArray()
  @IsOptional()
  @IsObject({ each: true })
  @ValidateNested({ each: true })
  files: null | AttachmentFile[];
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.

请看下面的 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 Swagger 生成器比以往更强大_软件开发工具

左侧是 NestJS 服务器代码,右侧是利用 SDK 的客户端代码。

如果你设置了 @nestia/sdk,不仅可以生成 OpenAPI (Swagger) 文档,还可以为客户端开发者生成 SDK (软件开发工具包) 库,包含严格类型定义的 fetch() 函数。

如上图右侧所示,客户端程序员可以通过 SDK 库非常方便且安全地开发 API 交互程序。这个 SDK 库也是通过 @nestia/sdk 分析编译级别的 TypeScript 源代码生成的。

如果你成功生成了 OpenAPI 文档,接下来可以挑战生成 SDK (软件开发工具包) 库。

Swagger-UI + TypeScript 编辑器

新的 NestJS Swagger 生成器比以往更强大_软件开发工具_02

 https://nestia.io/docs/editor/

如果你成功构建了 OpenAPI (Swagger) 文档,可以通过 Swagger-UI 提供给合作开发者。此外,如何将 Swagger-UI 与嵌入 SDK (软件开发工具包) 库的在线 TypeScript 编辑器结合起来呢?

只需访问上述网站 ( https://nestia.io/docs/editor/) 并将 Swagger 文件放入其中。然后,在线 TypeScript 编辑器 (StackBlitz) 将与 Swagger-UI 结合打开,客户端开发者可以更高效地使用它。