const express = require('express') const cors = require('cors') const helmet = require('helmet') const morgan = require('morgan') const rateLimit = require('express-rate-limit') const compression = require('compression') const path = require('path') require('dotenv').config() // 数据库连接 const { testConnection, syncModels } = require('./models') // 导入Swagger配置 const { specs, swaggerUi } = require('./config/swagger') const app = express() // 中间件配置 app.use(helmet()) // 安全头 app.use(cors()) // 跨域 app.use(compression()) // 压缩 app.use(morgan('combined')) // 日志 app.use(express.json({ limit: '10mb' })) app.use(express.urlencoded({ extended: true, limit: '10mb' })) // 限流 const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 分钟 max: 100, // 限制每个IP最多100个请求 message: { success: false, message: '请求过于频繁,请稍后重试' } }) app.use('/api', limiter) // 健康检查 app.get('/health', (req, res) => { res.json({ success: true, message: '服务运行正常', timestamp: new Date().toISOString(), version: process.env.npm_package_version || '1.0.0' }) }) // 配置Swagger UI app.use('/swagger', swaggerUi.serve, swaggerUi.setup(specs, { explorer: true, customCss: '.swagger-ui .topbar { background-color: #3B82F6; }', customSiteTitle: 'NiuMall API 文档' })) // 提供Swagger JSON文件 app.get('/api-docs-json', (req, res) => { res.setHeader('Content-Type', 'application/json') res.send(specs) }) const PORT = process.env.PORT || 4330 const startServer = async () => { try { // 测试数据库连接 const dbConnected = await testConnection(); if (!dbConnected) { console.error('❌ 数据库连接失败,服务器启动终止'); process.exit(1); } // 同步数据库模型 await syncModels(); app.listen(PORT, () => { console.log(`🚀 服务器启动成功`) console.log(`📱 运行环境: ${process.env.NODE_ENV || 'development'}`) console.log(`🌐 访问地址: http://localhost:${PORT}`) console.log(`📊 健康检查: http://localhost:${PORT}/health`) console.log(`📚 API文档: http://localhost:${PORT}/swagger`) console.log(`📄 API文档JSON: http://localhost:${PORT}/api-docs-json`) }) } catch (error) { console.error('❌ 服务器启动失败:', error) process.exit(1) } } startServer() // API 路由 app.use('/api/auth', require('./routes/auth')) app.use('/api/users', require('./routes/users')) app.use('/api/orders', require('./routes/orders')) app.use('/api/payments', require('./routes/payments'))