主要改进: - 新增配置管理 (server/config.js) - 新增日志工具 (server/utils/logger.js) - 添加全局错误处理中间件,统一错误响应格式 - 添加输入验证和 AppError 错误类 - 重构 db.js 迁移逻辑,代码更清晰 - 前端列表改为无限滚动加载,每页 20 条 - 封装 AppState 状态管理模块 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
83 lines
2.4 KiB
JavaScript
83 lines
2.4 KiB
JavaScript
const express = require('express');
|
|
const cors = require('cors');
|
|
const path = require('path');
|
|
const compression = require('compression');
|
|
|
|
const config = require('./config');
|
|
const logger = require('./utils/logger');
|
|
const db = require('./db');
|
|
const { router: authRouter, auth } = require('./routes/auth');
|
|
const statsRouter = require('./routes/stats');
|
|
const recordsRouter = require('./routes/records');
|
|
const ioRouter = require('./routes/io');
|
|
|
|
const app = express();
|
|
|
|
// 请求日志中间件
|
|
app.use(logger.requestLogger);
|
|
|
|
app.use(cors());
|
|
app.use(express.json());
|
|
app.use(compression());
|
|
app.use(express.static(path.join(__dirname, '..', 'public'), {
|
|
maxAge: '1h',
|
|
etag: true
|
|
}));
|
|
|
|
// 联系人自动补全
|
|
app.use('/api', (req, res, next) => {
|
|
res.setHeader('Cache-Control', 'no-cache');
|
|
next();
|
|
});
|
|
|
|
app.get('/api/contacts', auth, (req, res) => {
|
|
const field = req.query.field;
|
|
const allowed = ['boss', 'partner', 'source', 'destination'];
|
|
if (!field || !allowed.includes(field)) return res.status(400).json({ error: '无效字段' });
|
|
|
|
const rows = db.prepare(`
|
|
SELECT ${field} as name, MAX(created_at) as last_used, COUNT(*) as freq
|
|
FROM records WHERE user_id = ? AND ${field} IS NOT NULL AND ${field} != ''
|
|
GROUP BY ${field} ORDER BY MAX(created_at) DESC
|
|
`).all(req.user.id);
|
|
res.json(rows.map(r => r.name));
|
|
});
|
|
|
|
// 路由挂载
|
|
app.use('/api', authRouter);
|
|
app.use('/api/stats', auth, statsRouter);
|
|
app.use('/api/records', auth, recordsRouter);
|
|
app.use('/api', auth, ioRouter);
|
|
|
|
// 404 处理
|
|
app.use((req, res) => {
|
|
res.status(404).json({ error: '接口不存在' });
|
|
});
|
|
|
|
// 全局错误处理中间件
|
|
app.use((err, req, res, next) => {
|
|
// 记录错误日志
|
|
logger.error('Unhandled error:', err.message, err.stack);
|
|
|
|
// 处理特定错误类型
|
|
if (err.name === 'UnauthorizedError') {
|
|
return res.status(401).json({ error: '未授权访问' });
|
|
}
|
|
|
|
if (err.name === 'SyntaxError' && err.status === 400 && 'body' in err) {
|
|
return res.status(400).json({ error: 'JSON 格式错误' });
|
|
}
|
|
|
|
// 默认错误响应
|
|
const status = err.status || err.statusCode || 500;
|
|
const message = err.expose ? err.message : '服务器内部错误';
|
|
|
|
res.status(status).json({ error: message });
|
|
});
|
|
|
|
const PORT = config.port;
|
|
const HOST = config.host;
|
|
app.listen(PORT, HOST, () => {
|
|
logger.info(`服务器运行在 http://${HOST}:${PORT}`);
|
|
});
|