import { Controller, Get, UnauthorizedException } from '@nestjs/common'; import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger'; import type { Request } from 'express'; import { SwaggerService } from './swaggerService'; import { ConfigCenterService } from '../../services/configCenterService'; import { Req } from '@nestjs/common'; @ApiTags('文档') @Controller() export class SwaggerController { constructor( private readonly docs: SwaggerService, private readonly configCenter: ConfigCenterService, ) {} private verifyToken(req: Request) { const requiredToken = this.configCenter.get('swagger.token', ''); if (!requiredToken) { throw new UnauthorizedException('Swagger token not configured'); } const auth = req.headers['authorization'] || ''; const token = typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice('Bearer '.length).trim() : ''; if (token !== requiredToken) { throw new UnauthorizedException('Invalid token'); } } @Get('api-json') @ApiOperation({ summary: '获取完整 API 文档 JSON' }) @ApiResponse({ status: 200, description: '返回完整 Swagger 文档 JSON' }) getDocsJson(@Req() req: Request) { this.verifyToken(req); return this.docs.getDocument(); } @Get('api/admin-json') @ApiOperation({ summary: '获取管理端 API 文档 JSON' }) @ApiResponse({ status: 200, description: '返回管理端 Swagger 文档 JSON' }) getAdminDocsJson(@Req() req: Request) { this.verifyToken(req); return this.docs.getAdminDocument(); } @Get('api/frontend-json') @ApiOperation({ summary: '获取前端 API 文档 JSON' }) @ApiResponse({ status: 200, description: '返回前端 Swagger 文档 JSON' }) getFrontendDocsJson(@Req() req: Request) { this.verifyToken(req); return this.docs.getFrontendDocument(); } }