|
|
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())
|
|
|
|
|
|
|
|
|
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 }
|
|
|
|