123 lines
3.2 KiB
JavaScript
123 lines
3.2 KiB
JavaScript
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 文档'
|
|
}))
|
|
|
|
// 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/suppliers', require('./routes/suppliers'))
|
|
app.use('/api/transport', require('./routes/transport'))
|
|
app.use('/api/finance', require('./routes/finance'))
|
|
app.use('/api/quality', require('./routes/quality'))
|
|
|
|
// 静态文件服务
|
|
app.use('/static', express.static('public'));
|
|
|
|
// API文档路由重定向
|
|
app.get('/docs', (req, res) => {
|
|
res.redirect('/swagger');
|
|
});
|
|
|
|
// 404 处理
|
|
app.use((req, res) => {
|
|
res.status(404).json({
|
|
success: false,
|
|
message: '接口不存在',
|
|
path: req.path
|
|
})
|
|
})
|
|
|
|
// 错误处理中间件
|
|
app.use((err, req, res, next) => {
|
|
console.error('Error:', err)
|
|
|
|
res.status(err.status || 500).json({
|
|
success: false,
|
|
message: err.message || '服务器内部错误',
|
|
timestamp: new Date().toISOString(),
|
|
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
|
|
})
|
|
})
|
|
|
|
const PORT = process.env.PORT || 3000
|
|
|
|
// 启动服务器
|
|
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`)
|
|
})
|
|
} catch (error) {
|
|
console.error('❌ 服务器启动失败:', error)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
startServer()
|