perf: add rate limiting, validation, logging, and error handling

- Add express-rate-limit with tiered rate limits per endpoint
- Add express-validator for input validation on all API routes
- Add winston + morgan for structured logging
- Add node-cache for lottery result caching (5min TTL, 1000 max keys)
- Convert OCR to async task queue with max 2 concurrent jobs
- Add global error handler middleware
- Add React ErrorBoundary for client-side error handling
- Fix memory leaks in OCR task queue and lottery cache
- Add per-item error handling in batch ticket updates
- Fix SQL UPDATE to include user_id in WHERE clause

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Developer
2026-03-19 11:35:12 +08:00
co-authored by Claude Opus 4.6
parent 7b1073e23b
commit 335f0fb8dc
17 changed files with 927 additions and 148 deletions
+14 -20
View File
@@ -2,6 +2,8 @@ const express = require('express');
const db = require('../db/init');
const { authMiddleware } = require('../middleware/auth');
const { getEstimatedDrawTime } = require('../services/lottery');
const { validate, ticketCreateRules, ticketUpdateRules, idParamRule } = require('../middleware/validate');
const logger = require('../services/logger');
const router = express.Router();
@@ -16,7 +18,6 @@ router.get('/', (req, res) => {
SELECT * FROM tickets WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?
`).all(req.user.id, limit, offset);
// 为未开奖彩票添加预计开奖时间
const ticketsWithDrawTime = tickets.map(ticket => {
if (ticket.status === 'pending' && ticket.game && ticket.issue) {
return {
@@ -57,13 +58,9 @@ router.get('/stats', (req, res) => {
});
// 添加彩票
router.post('/', (req, res) => {
router.post('/', ticketCreateRules, validate, (req, res) => {
const { type, game, issue, numbers, bet_count, multiple, is_additional, cost, image_path } = req.body;
if (!type || !game || !cost) {
return res.status(400).json({ error: '缺少必要字段' });
}
const stmt = db.prepare(`
INSERT INTO tickets (user_id, type, game, issue, numbers, bet_count, multiple, is_additional, cost, image_path)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -75,11 +72,12 @@ router.post('/', (req, res) => {
bet_count || 1, multiple || 1, is_additional ? 1 : 0, cost, image_path || null
);
logger.info(`添加彩票: userId=${req.user.id}, game=${game}, cost=${cost}`);
res.json({ id: result.lastInsertRowid, message: '添加成功' });
});
// 更新彩票
router.put('/:id', (req, res) => {
router.put('/:id', idParamRule, validate, (req, res) => {
const { id } = req.params;
const { type, game, issue, numbers, bet_count, multiple, is_additional, cost, prize, status } = req.body;
@@ -90,7 +88,7 @@ router.put('/:id', (req, res) => {
const stmt = db.prepare(`
UPDATE tickets SET type = ?, game = ?, issue = ?, numbers = ?, bet_count = ?, multiple = ?, is_additional = ?, cost = ?, prize = ?, status = ?
WHERE id = ?
WHERE id = ? AND user_id = ?
`);
stmt.run(
type ?? ticket.type,
@@ -103,35 +101,31 @@ router.put('/:id', (req, res) => {
cost ?? ticket.cost,
prize ?? ticket.prize,
status ?? ticket.status,
id
id,
req.user.id
);
logger.info(`更新彩票: id=${id}`);
res.json({ message: '更新成功' });
});
// 删除彩票
router.delete('/:id', (req, res) => {
router.delete('/:id', idParamRule, validate, (req, res) => {
const { id } = req.params;
const ticketId = Number(id);
console.log('删除请求:', { id, ticketId, userId: req.user.id });
if (isNaN(ticketId)) {
return res.status(400).json({ error: '无效的ID' });
}
const ticketId = Number(id); // idParamRule 已验证 id 为正整数
try {
const result = db.prepare('DELETE FROM tickets WHERE id = ? AND user_id = ?').run(ticketId, req.user.id);
console.log('删除结果:', result);
if (result.changes === 0) {
return res.status(404).json({ error: '彩票不存在' });
}
logger.info(`删除彩票: id=${ticketId}`);
res.json({ message: '删除成功' });
} catch (err) {
console.error('删除错误:', err);
res.status(500).json({ error: '删除失败: ' + err.message });
logger.error('删除彩票失败', { error: err.message });
res.status(500).json({ error: '删除失败' });
}
});