oauth_nest_demo/src/main.ts

100 lines
3.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
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: true, // 允许所有来源
credentials: true, // 允许携带凭证
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], // 明确指定允许的 HTTP 方法
allowedHeaders: [
'Content-Type',
'Authorization',
'Accept',
'Origin',
'Referer',
'User-Agent',
], // 允许的请求头
});
// 注册全局异常过滤器
app.useGlobalFilters(new HttpExceptionFilter());
// 注册全局响应转换拦截器
app.useGlobalInterceptors(new TransformInterceptor());
// 注册全局验证管道
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // 自动删除非 DTO 定义的属性
forbidNonWhitelisted: true, // 如果有非白名单属性,抛出错误
transform: true, // 自动转换类型
}),
);
// 使用 NestJS 内置方法设置限制
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
// Swagger 文档配置
const config = new DocumentBuilder()
.setTitle('我的应用 API')
.setDescription('这是我的应用程序的 API 文档')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3030);
console.log('✅ 应用启动成功,监听端口 3030');
} catch (error) {
console.error('❌ 应用启动失败:', error);
process.exit(1);
}
}
bootstrap();