Nodejs Nestjs插件swagger-jsdoc生成API文档的使用

Nodejs Nestjs插件swagger-jsdoc生成API文档的使用
swagger-jsdoc 是一个用于将 JSDoc 注释转换为 Swagger 文档的库。在 NestJS 项目中,你可以结合 swagger-jsdocswagger-ui-express 来生成和展示 API 文档。下面是如何在 NestJS 项目中使用 swagger-jsdoc 的步骤。

步骤 1: 安装必要的依赖

首先,你需要安装 swagger-jsdocswagger-ui-express

npm install swagger-jsdoc swagger-ui-express

步骤 2: 配置 Swagger

创建一个配置文件(例如 swagger-config.js),定义你的 Swagger 配置:

const swaggerJSDoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'NestJS API',
      version: '1.0.0',
      description: 'A simple NestJS API with Swagger documentation',
    },
    servers: [
      {
        url: 'http://localhost:3000',
      },
    ],
  },
  apis: ['./src/**/*.ts'], // 指定包含注释的文件路径
};

const swaggerSpec = swaggerJSDoc(options);

module.exports = swaggerSpec;

步骤 3: 在 NestJS 应用中集成 Swagger

在你的 NestJS 应用中,你可以在主模块(通常是 app.module.ts)中设置 Swagger:

import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as express from 'express';
import * as swaggerUi from 'swagger-ui-express';
import swaggerSpec from './swagger-config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 设置 Swagger UI
  app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

  await app.listen(3000);
}
bootstrap();

步骤 4: 添加 JSDoc 注释到控制器

在你的控制器中添加 JSDoc 注释来描述 API 路由、参数和响应:

/**
 * @openapi
 * /users:
 *   get:
 *     summary: Get all users
 *     tags:
 *       - Users
 *     responses:
 *       200:
 *         description: A list of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/User'
 */
@Controller('users')
export class UsersController {
  @Get()
  findAll(): User[] {
    // 返回用户列表
  }
}

步骤 5: 运行应用并访问 Swagger UI

启动你的 NestJS 应用后,打开浏览器并访问 http://localhost:3000/api-docs,你应该能看到生成的 Swagger 文档页面。

以上就是如何在 NestJS 中使用 swagger-jsdoc 生成 API 文档的基本步骤。通过这种方式,你可以轻松地为你的 API 添加详细的文档说明,并且这些文档会随着你的代码自动更新。


3 回复

当然,乐于助您!使用swagger-jsdoc在NestJS项目中生成API文档,可以让你的应用像自带说明书一样清晰易懂。首先,你需要安装swagger-jsdocswagger-ui-express,这两个是生成和展示文档的好帮手。

然后,在你的NestJS应用中配置swagger-jsdoc。你可以创建一个模块,比如叫docs.module.ts,在这个模块里设置Swagger:

import { Module } from '@nestjs/common';
import * as swaggerJSDoc from 'swagger-jsdoc';
import * as swaggerUi from 'swagger-ui-express';

@Module({
  providers: [],
})
export class DocsModule {
  configure() {
    const options = {
      definition: {
        openapi: '3.0.0',
        info: { title: 'API Documentation', version: '1.0.0' },
      },
      apis: ['./src/**/*.ts'], // 这里指定你的注释文件路径
    };

    const swaggerSpec = swaggerJSDoc(options);
    return (app) => {
      app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
    };
  }
}

别忘了在你的主模块(通常是app.module.ts)中导入DocsModule,这样你的API文档就准备好了!

最后,记得在你的控制器方法上添加JSDoc注释来描述你的API。例如:

/**
 * @openapi
 * /hello:
 *   get:
 *     description: Returns a greeting message
 *     responses:
 *       200:
 *         description: A successful response
 */
@Controller()
export class AppController {
  @Get('hello')
  getHello(): string {
    return 'Hello World!';
  }
}

这样,当你访问/api-docs时,就能看到你精心准备的API文档啦!希望这能帮你更好地组织和分享你的API接口信息。


在NestJS中使用swagger-jsdoc来生成API文档是一种常见的做法。swagger-jsdoc可以与@nestjs/swagger库一起使用,以实现更强大的API文档自动生成。下面是一个简单的步骤指南和示例代码,展示如何在你的NestJS项目中设置和使用swagger-jsdoc

步骤 1: 安装必要的依赖

首先,你需要安装@nestjs/swaggerswagger-jsdoc以及他们的相关依赖:

npm install @nestjs/swagger swagger-ui-express swagger-jsdoc

步骤 2: 配置Swagger

接下来,在你的应用程序中配置Swagger。这通常通过创建一个模块或在现有的模块中添加配置来完成。

创建Swagger配置文件(可选)

你也可以将Swagger配置放入一个单独的文件中,例如swagger.config.js

// swagger.config.js
const swaggerJSDoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'API 文档',
      version: '1.0.0',
    },
  },
  apis: ['./src/**/*.ts'], // 指定包含注释的文件路径
};

module.exports = swaggerJSDoc(options);

步骤 3: 在模块中集成Swagger

然后,在你的NestJS模块中集成Swagger。通常,你会这样做:

import { Module } from '@nestjs/common';
import { NestjsSwaggerModule } from '@nestjs/swagger';
import * as swaggerConfig from './swagger.config';

@Module({
  imports: [
    NestjsSwaggerModule.forRoot({
      swaggerOptions: {
        persistAuthorization: true,
      },
      swaggerJsdoc: swaggerConfig, // 使用配置
    }),
  ],
})
export class AppModule {}

注意:确保导入正确的模块名称,这里假设是NestjsSwaggerModule,如果你使用的是@nestjs/swagger,则应相应调整。

步骤 4: 添加API文档注解

最后,为你的控制器添加API文档注解。你可以使用@ApiTags, @ApiOperation, @ApiResponse等装饰器来自定义API文档。

import { Controller, Get, Param, Query } from '@nestjs/common';
import { ApiOperation, ApiTags, ApiResponse } from '@nestjs/swagger';

@ApiTags('示例')
@Controller('example')
export class ExampleController {

  @Get()
  @ApiOperation({ summary: '获取示例列表' })
  @ApiResponse({ status: 200, description: '成功响应' })
  findAll(@Query() query) {
    return [];
  }

}

以上步骤就完成了基本的Swagger配置和API文档的自动生成。通过这种方式,你可以让NestJS应用自动根据你的代码生成详细的API文档,极大地提高了开发效率和文档维护的便利性。

swagger-jsdoc 可以与 NestJS 结合使用来生成 API 文档。首先,安装必要的包:

npm install --save swagger-jsdoc @nestjs/swagger

然后,在你的应用中配置 swagger-jsdoc

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

const config = new DocumentBuilder()
  .setTitle('你的项目名称')
  .setDescription('项目描述')
  .setVersion('1.0')
  .addTag('标签名称')
  .build();
const documentation = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, documentation);

在需要生成文档的方法上添加装饰器,例如:

@Get()
@ApiOperation({ summary: '获取列表' })
@ApiResponse({ status: 200, description: '成功' })
async get() {
  // ...
}

这样就可以自动生成 API 文档了。

回到顶部