| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- import 'reflect-metadata';
- import express, { Express } from 'express';
- import cors from 'cors';
- import helmet from 'helmet';
- import compression from 'compression';
- import rateLimit from 'express-rate-limit';
- import * as dotenv from 'dotenv';
- import { initializeDatabase, closeDatabase } from './config/database';
- import routes from './routes';
- import { loggerMiddleware } from './middlewares/logger.middleware';
- import { errorMiddleware, notFoundMiddleware } from './middlewares/error.middleware';
- // 加载环境变量
- dotenv.config();
- const app: Express = express();
- const PORT = process.env.PORT || 3000;
- const API_PREFIX = process.env.API_PREFIX || '/api';
- // ========================================
- // 中间件配置
- // ========================================
- // 安全头部
- app.use(helmet());
- // 压缩响应
- app.use(compression());
- // CORS配置
- app.use(cors({
- origin: process.env.CORS_ORIGIN || 'http://localhost:4200',
- credentials: true
- }));
- // 请求体解析
- app.use(express.json({ limit: '10mb' }));
- app.use(express.urlencoded({ extended: true, limit: '10mb' }));
- // 请求日志
- app.use(loggerMiddleware);
- // 限流配置
- const limiter = rateLimit({
- windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000'), // 15分钟
- max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS || '100'), // 最多100个请求
- message: {
- success: false,
- message: '请求过于频繁,请稍后再试'
- }
- });
- app.use(API_PREFIX, limiter);
- // ========================================
- // 路由配置
- // ========================================
- app.use(API_PREFIX, routes);
- // ========================================
- // 错误处理
- // ========================================
- app.use(notFoundMiddleware);
- app.use(errorMiddleware);
- // ========================================
- // 启动服务器
- // ========================================
- const startServer = async () => {
- try {
- // 初始化数据库连接
- await initializeDatabase();
- // 启动HTTP服务器
- app.listen(PORT, () => {
- console.log('========================================');
- console.log('🚀 数智健调系统后端API启动成功');
- console.log('========================================');
- console.log(`📡 服务器地址: http://localhost:${PORT}`);
- console.log(`🔗 API地址: http://localhost:${PORT}${API_PREFIX}`);
- console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
- console.log(`📊 数据库: ${process.env.DB_DATABASE}`);
- console.log('========================================');
- });
- // 优雅关闭
- process.on('SIGTERM', gracefulShutdown);
- process.on('SIGINT', gracefulShutdown);
- } catch (error) {
- console.error('❌ 服务器启动失败:', error);
- process.exit(1);
- }
- };
- /**
- * 优雅关闭
- */
- const gracefulShutdown = async () => {
- console.log('\n正在关闭服务器...');
-
- try {
- await closeDatabase();
- console.log('✅ 服务器已安全关闭');
- process.exit(0);
- } catch (error) {
- console.error('❌ 关闭服务器时发生错误:', error);
- process.exit(1);
- }
- };
- // 启动服务器
- startServer();
- export default app;
|