import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as mysql from 'mysql2/promise'; import { ConfigService } from '@nestjs/config'; import * as dotenv from 'dotenv'; import { HttpExceptionFilter } from './common/filters/http-exception.filter'; import { TransformInterceptor } from './common/interceptors/transform.interceptor'; import * as bodyParser from 'body-parser'; dotenv.config(); // 创建数据库的函数 async function createDatabaseIfNotExists() { try { // 连接 MySQL(不指定数据库) const connection = await mysql.createConnection({ host: process.env.SERVER_HOST, user: process.env.SERVER_USER, password: process.env.PASSWORD, }); console.log('🔌 连接到 MySQL 服务器成功'); // 创建数据库(如果不存在) await connection.query('CREATE DATABASE IF NOT EXISTS auth_db'); console.log('✅ 数据库 auth_db 创建成功或已存在'); await connection.end(); console.log('🔌 关闭数据库连接'); } catch (error) { console.error('❌ 创建数据库失败:', error); throw error; } } async function bootstrap() { try { // 1. 首先创建数据库 await createDatabaseIfNotExists(); // 2. 然后启动 Nest 应用(此时数据库已存在) console.log('🚀 启动 NestJS 应用...'); const app = await NestFactory.create(AppModule); const configService = app.get(ConfigService); // 获取 ConfigService 实例 app.enableCors({ origin: ['http://108.171.193.155:8000', 'http://localhost:8000'], // 指定允许的前端地址 credentials: true, // 允许携带凭证 methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], // 允许的 HTTP 方法 allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'Origin', 'Referer', 'User-Agent'], // 允许的请求头 }); // 注册全局异常过滤器 app.useGlobalFilters(new HttpExceptionFilter()); // 注册全局响应转换拦截器 app.useGlobalInterceptors(new TransformInterceptor()); // 使用 NestJS 内置方法设置限制 app.use(bodyParser.json({ limit: '50mb' })); app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); await app.listen(3030); console.log('✅ 应用启动成功,监听端口 3030'); } catch (error) { console.error('❌ 应用启动失败:', error); process.exit(1); } } bootstrap();