$ npm install --save @nestjs/swagger
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
import './init/init';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { getLogger } from 'xmcommon';
import { NestLogger } from './common/nest.logger';
import { RequestInterceptor } from './common/request.interceptor';
import { HttpFilterFilter } from './common/http_filter.filter';
import { NestExpressApplication } from '@nestjs/platform-express';
import session from 'express-session';
import path from 'path';
import { AuthGuard } from './common/auth.guard';
import { EnvUtils } from './env_utils';
import { ConfigUtils } from './init/config_utils';
import { ValidationPipe } from './common/validation_pipe';
const log = getLogger(__filename);
log.info('程序开始启动... 当前环境:' + EnvUtils.env + ' 开发环境:' + EnvUtils.isDev);
async function bootstrap() {
const globalConfig = ConfigUtils.getConfig();
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
logger: new NestLogger(),
});
app.use(session(ConfigUtils.buildSessionOptions()));
// app.useStaticAssets(path.join(process.cwd(), 'public'), { prefix: '/static/' });
app.useStaticAssets(path.join(process.cwd(), 'public'), {});
app.setBaseViewsDir(path.join(process.cwd(), 'view')); // 放视图的文件
app.setViewEngine('ejs');
app.useGlobalPipes(new ValidationPipe());
app.useGlobalInterceptors(new RequestInterceptor());
app.useGlobalFilters(new HttpFilterFilter());
app.useGlobalGuards(new AuthGuard());
if (EnvUtils.isDev) {
// 如果是开发模式,则加载文档
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { DocumentBuilder, SwaggerModule } = require('@nestjs/swagger');
const config = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('apidoc', app, document);
log.info(`swagger url: http://localhost:4000/apidoc`);
}
await app.listen(4000);
log.info(`开始侦听:4000...`);
}
bootstrap();
import { Controller, Get } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AppService } from './app.service';
@ApiTags('应用系列接口')
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@ApiOperation({ summary: '返回hello' })
@ApiResponse({ type: String })
getHello(): string {
return this.appService.getHello();
}
}
$ run run start
@ApiTags('登录相关接口')
@Controller('login')
export class CLoginController {}
@ApiProperty({ title: '手机号', maxLength: 11, minLength: 11 })
@ApiBearerAuth('JWT')
apifox的请求参数
auth类型列表
@ApiOperation({ summary: '使用验证码登录', description: '要求先获得验证码' })
// 登录返回的VO
@ApiTags('登录返回的VO')
export class XDoLoginVO extends XRetVO {
@ApiProperty({ title: '具体返回的数据 ' })
data?: XTokenInfo;
}
// 使用验证码登录的请求参数
@ApiTags('使用验证码登录的请求参数')
export class XDTODoLogin {
@ApiProperty({ title: '手机号', maxLength: 11, minLength: 11 })
mobile: string;
@ApiProperty({ title: '验证码', maxLength: 8, minLength: 1 })
code: string;
}
// 登录请求
@Post('login')
@ApiOperation({ summary: '使用验证码登录', description: '要求先获得验证码' })
@ApiOkResponse({ type: XDoLoginVO })
private async doLogin(@Body() paramBody: XDTODoLogin) {
const r = new XCommonRet();
do {
const result = (await this.user.adminLogin(
paramBody.mobile,
paramBody.code,
)) as XCommonRet<ITokenString>;
r.assignFrom(result);
} while (false);
return r;
}
@ApiOkResponse()
@ApiCreatedResponse()
@ApiAcceptedResponse()
@ApiNoContentResponse()
@ApiMovedPermanentlyResponse()
@ApiFoundResponse()
@ApiBadRequestResponse()
@ApiUnauthorizedResponse()
@ApiNotFoundResponse()
@ApiForbiddenResponse()
@ApiMethodNotAllowedResponse()
@ApiNotAcceptableResponse()
@ApiRequestTimeoutResponse()
@ApiConflictResponse()
@ApiPreconditionFailedResponse()
@ApiTooManyRequestsResponse()
@ApiGoneResponse()
@ApiPayloadTooLargeResponse()
@ApiUnsupportedMediaTypeResponse()
@ApiUnprocessableEntityResponse()
@ApiInternalServerErrorResponse()
@ApiNotImplementedResponse()
@ApiBadGatewayResponse()
@ApiServiceUnavailableResponse()
@ApiGatewayTimeoutResponse()
@ApiDefaultResponse()
每次都用apifox更新接口文档是一个很痛苦的事情,还好有可以导入
apifox可以支持很多种导入,这里只针对nestjs集成的swagger
用apifox创建一个项目后,再点导入
显示导入选择框,可以看到apifox集居了很多种格式的导入, 这里选择OpenAPI/Swagger和URL导入
选择URL试,输入URL http://localhost:3000/api-json
然后会弹出导出导入预览,第一次导入默认就可以了,然后点确认导入
完后会弹出一个导入成功的按钮
最后点在接口管理,就可以看到你导入的接口了
这样我们就完成了导入