import { ValidationPipe } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import * as express from 'express'; import { AppModule } from './app.module'; import { AllExceptionsFilter } from './common/filters/all-exceptions.filter'; import { TransformInterceptor } from './common/interceptors/transform.interceptor'; async function bootstrap(): Promise { // 设计清单 designData 契约上限 1MB(api-contract-v1 §5), // body 限制放宽到 2MB,超 1MB 的业务校验在 design-list service 返回 400 const app = await NestFactory.create(AppModule, { bodyParser: false }); app.use(express.json({ limit: '2mb' })); app.use(express.urlencoded({ extended: true, limit: '2mb' })); const config = app.get(ConfigService); app.setGlobalPrefix('api', { exclude: ['health'] }); app.enableCors(); // 全局管道:剥离未声明字段 + 自动类型转换 + 拒绝多余字段 app.useGlobalPipes( new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true, }), ); // 统一响应包裹 + 统一异常输出 app.useGlobalInterceptors(new TransformInterceptor()); app.useGlobalFilters(new AllExceptionsFilter()); // Swagger 文档,生产环境可置空 SWAGGER_PATH 关闭 const swaggerPath = config.get('app.swaggerPath'); if (swaggerPath) { const docConfig = new DocumentBuilder() .setTitle('wxmp-backend API') .setDescription('微信小程序后端接口文档') .setVersion('0.1.0') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, docConfig); SwaggerModule.setup(swaggerPath, app, document); } const port = config.get('app.port') ?? 3000; await app.listen(port); // eslint-disable-next-line no-console console.log(`应用已启动: http://localhost:${port} | Swagger: /${swaggerPath}`); } void bootstrap();