const express = require('express') const cors = require('cors') const { SERVER_CONFIG } = require('./config') const modelRouter = require('./router/model') const chatRouter = require('./router/chat') const logger = require('./lib/logger') const app = express() app.use(cors()) // 增加请求体积限制,设置为128MB app.use(express.json({ limit: '128mb' })) app.use(express.urlencoded({ extended: true, limit: '128mb' })) app.use(express.raw({ limit: '128mb' })) // 注册路由 app.use('/v1/models', modelRouter) app.use('/v1/chat', chatRouter) // 健康检查端点 app.get('/health', (req, res) => { res.json({ status: 'ok', timestamp: new Date().toISOString(), uptime: process.uptime() }) }) // 全局错误处理中间件 app.use((error, req, res, next) => { logger.logGlobalError('UNHANDLED_ERROR', error.message, { stack: error.stack, url: req.url, method: req.method }) res.status(500).json({ error: { message: '服务器内部错误', type: 'server_error' } }) }) // 全局异常捕获 process.on('uncaughtException', (error) => { logger.logGlobalError('UNCAUGHT_EXCEPTION', error.message, { stack: error.stack }) console.error('未捕获的异常:', error) process.exit(1) }) process.on('unhandledRejection', (reason, promise) => { logger.logGlobalError('UNHANDLED_REJECTION', String(reason), { promise: promise.toString() }) console.error('未处理的 Promise 拒绝:', reason) }) // 优雅关闭处理 process.on('SIGTERM', () => { console.log('收到 SIGTERM 信号,开始优雅关闭...') process.exit(0) }) process.on('SIGINT', () => { console.log('收到 SIGINT 信号,开始优雅关闭...') process.exit(0) }) // 启动服务器 const server = app.listen(SERVER_CONFIG.PORT, () => { logger.logInfo('服务器启动', '服务器启动成功', { 端口: SERVER_CONFIG.PORT, 地址: `http://localhost:${SERVER_CONFIG.PORT}`, Node版本: process.version, 操作系统: process.platform }) console.log(`服务已启动在 http://localhost:${SERVER_CONFIG.PORT}`) }) module.exports = { app, server }