refactor: API 请求整合与 Bug 修复
前端重构: - 新增 api/ 目录统一管理所有 API 请求 - 所有 stores 和 pages 改为使用 api 模块 - 修复日期格式化函数,支持 Date 对象和 ISO 字符串 - 修复 TransactionItem 使用 CategoryIcon 组件 - 优化 ChartWrapper 区分 H5 和小程序环境 后端修复: - 修复 auth 中间件 PUBLIC_PATHS 缺少 demo-login - 修复备份工具命令注入漏洞,改用 execFile - 修复 stats 路由 type 参数验证 - 优化分类排序为批量 SQL 更新 - 合并迁移和删除为数据库事务原子操作 - 修复交易和统计日期返回格式 - 新增自动备份功能(启动时备份)
This commit is contained in:
@@ -1,12 +1,21 @@
|
||||
# Server
|
||||
PORT=3000
|
||||
|
||||
# Security
|
||||
TOKEN_SECRET=your_random_secret_here
|
||||
|
||||
# CORS (comma-separated origins, empty = allow all)
|
||||
CORS_ORIGINS=
|
||||
|
||||
# MySQL
|
||||
DB_HOST=your_mysql_host_here
|
||||
DB_USER=your_mysql_user_here
|
||||
DB_PASSWORD=your_mysql_password_here
|
||||
DB_NAME=your_mysql_name_here
|
||||
|
||||
# Backup
|
||||
BACKUP_DIR=/var/backups/xiaocai
|
||||
|
||||
# WeChat Mini Program
|
||||
WX_APPID=your_wx_appid_here
|
||||
WX_SECRET=your_wx_secret_here
|
||||
|
||||
@@ -10,6 +10,8 @@ import transactionRoutes from './routes/transaction'
|
||||
import statsRoutes from './routes/stats'
|
||||
import budgetRoutes from './routes/budget'
|
||||
import categoryRoutes from './routes/category'
|
||||
import backupRoutes from './routes/backup'
|
||||
import { backupDatabase } from './utils/backup'
|
||||
|
||||
// Warn if token secret is using default fallback
|
||||
if (!process.env.TOKEN_SECRET) {
|
||||
@@ -59,6 +61,7 @@ app.use('/api/transactions', apiLimiter, transactionRoutes)
|
||||
app.use('/api/stats', apiLimiter, statsRoutes)
|
||||
app.use('/api/budget', apiLimiter, budgetRoutes)
|
||||
app.use('/api/categories', apiLimiter, categoryRoutes)
|
||||
app.use('/api/backup', apiLimiter, backupRoutes)
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
try {
|
||||
@@ -71,7 +74,15 @@ app.get('/api/health', async (_req, res) => {
|
||||
|
||||
let server: any
|
||||
|
||||
initDatabase().then(() => {
|
||||
initDatabase().then(async () => {
|
||||
// 每次启动时自动备份数据库
|
||||
try {
|
||||
await backupDatabase()
|
||||
console.log('[Backup] 启动备份完成')
|
||||
} catch (err) {
|
||||
console.error('[Backup] 启动备份失败:', err)
|
||||
}
|
||||
|
||||
server = app.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`)
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ const TOKEN_SECRET = process.env.TOKEN_SECRET || 'xiaocai-token-secret-change-in
|
||||
const TOKEN_EXPIRY = 30 * 24 * 60 * 60 * 1000 // 30 days
|
||||
|
||||
// 不需要认证的路径
|
||||
const PUBLIC_PATHS = ['/api/auth/login', '/api/health']
|
||||
const PUBLIC_PATHS = ['/api/auth/login', '/api/auth/demo-login', '/api/health']
|
||||
|
||||
export function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
|
||||
// 公开路径跳过认证
|
||||
|
||||
29
server/src/routes/backup.ts
Normal file
29
server/src/routes/backup.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Router, Response } from 'express'
|
||||
import { AuthRequest } from '../middleware/auth'
|
||||
import { backupDatabase, getBackupList } from '../utils/backup'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 手动触发备份
|
||||
router.post('/', async (_req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const filepath = await backupDatabase()
|
||||
res.json({ code: 0, data: { filepath } })
|
||||
} catch (err) {
|
||||
console.error('[Backup] 手动备份失败:', err)
|
||||
res.status(500).json({ code: 50000, message: '备份失败' })
|
||||
}
|
||||
})
|
||||
|
||||
// 获取备份列表
|
||||
router.get('/', async (_req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const list = getBackupList()
|
||||
res.json({ code: 0, data: list })
|
||||
} catch (err) {
|
||||
console.error('[Backup] 获取列表失败:', err)
|
||||
res.status(500).json({ code: 50000, message: '获取备份列表失败' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -38,6 +38,27 @@ router.post('/', async (req: AuthRequest, res: Response) => {
|
||||
}
|
||||
})
|
||||
|
||||
// 更新自定义分类
|
||||
router.put('/:id', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { name, color } = req.body
|
||||
if (!name || !color) {
|
||||
return res.status(400).json({ code: 40001, message: '缺少必要参数' })
|
||||
}
|
||||
const [result] = await pool.query(
|
||||
'UPDATE categories SET name = ?, color = ? WHERE id = ? AND is_custom = 1 AND user_id = ?',
|
||||
[name, color, req.params.id, req.userId]
|
||||
)
|
||||
if ((result as any).affectedRows === 0) {
|
||||
return res.status(404).json({ code: 40400, message: '分类不存在' })
|
||||
}
|
||||
res.json({ code: 0 })
|
||||
} catch (err) {
|
||||
console.error('[Category] PUT error:', err)
|
||||
res.status(500).json({ code: 50000, message: '服务器错误' })
|
||||
}
|
||||
})
|
||||
|
||||
// 查询分类关联的记录数
|
||||
router.get('/:id/transaction-count', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
@@ -52,6 +73,72 @@ router.get('/:id/transaction-count', async (req: AuthRequest, res: Response) =>
|
||||
}
|
||||
})
|
||||
|
||||
// 迁移分类关联的记录到目标分类,并删除原分类(原子操作)
|
||||
router.post('/:id/migrate', async (req: AuthRequest, res: Response) => {
|
||||
const conn = await pool.getConnection()
|
||||
try {
|
||||
const { targetId } = req.body
|
||||
if (!targetId) {
|
||||
return res.status(400).json({ code: 40001, message: '缺少目标分类ID' })
|
||||
}
|
||||
|
||||
await conn.beginTransaction()
|
||||
|
||||
// 验证目标分类存在且属于当前用户或是默认分类
|
||||
const [targetRows] = await conn.query(
|
||||
'SELECT id FROM categories WHERE id = ? AND (user_id = 0 OR user_id = ?)',
|
||||
[targetId, req.userId]
|
||||
)
|
||||
if ((targetRows as any[]).length === 0) {
|
||||
await conn.rollback()
|
||||
return res.status(404).json({ code: 40400, message: '目标分类不存在' })
|
||||
}
|
||||
|
||||
// 迁移记录
|
||||
await conn.query(
|
||||
'UPDATE transactions SET category_id = ? WHERE category_id = ? AND user_id = ?',
|
||||
[targetId, req.params.id, req.userId]
|
||||
)
|
||||
|
||||
// 删除原分类
|
||||
await conn.query(
|
||||
'DELETE FROM categories WHERE id = ? AND is_custom = 1 AND user_id = ?',
|
||||
[req.params.id, req.userId]
|
||||
)
|
||||
|
||||
await conn.commit()
|
||||
res.json({ code: 0 })
|
||||
} catch (err) {
|
||||
await conn.rollback()
|
||||
console.error('[Category] migrate error:', err)
|
||||
res.status(500).json({ code: 50000, message: '服务器错误' })
|
||||
} finally {
|
||||
conn.release()
|
||||
}
|
||||
})
|
||||
|
||||
// 更新分类排序(批量更新,使用 CASE WHEN 一次完成)
|
||||
router.put('/sort', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { ids } = req.body // [id1, id2, id3, ...]
|
||||
if (!Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ code: 40001, message: '参数无效' })
|
||||
}
|
||||
|
||||
// 构建 CASE WHEN 语句批量更新
|
||||
const cases = ids.map((id: number, index: number) => `WHEN ${Number(id)} THEN ${index}`).join(' ')
|
||||
const idList = ids.map((id: number) => Number(id)).join(',')
|
||||
await pool.query(
|
||||
`UPDATE categories SET sort_order = CASE id ${cases} END WHERE id IN (${idList}) AND (user_id = 0 OR user_id = ?)`,
|
||||
[req.userId]
|
||||
)
|
||||
res.json({ code: 0 })
|
||||
} catch (err) {
|
||||
console.error('[Category] sort error:', err)
|
||||
res.status(500).json({ code: 50000, message: '服务器错误' })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const [result] = await pool.query(
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AuthRequest } from '../middleware/auth'
|
||||
import { getCurrentMonth, getMonthRange } from '../utils/date'
|
||||
|
||||
const router = Router()
|
||||
const VALID_TYPES = ['expense', 'income']
|
||||
|
||||
router.get('/overview', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
@@ -54,6 +55,9 @@ router.get('/overview', async (req: AuthRequest, res: Response) => {
|
||||
router.get('/category', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { month, type = 'expense' } = req.query
|
||||
if (!VALID_TYPES.includes(type as string)) {
|
||||
return res.status(400).json({ code: 40002, message: '类型无效' })
|
||||
}
|
||||
const m = (month as string) || getCurrentMonth()
|
||||
const range = getMonthRange(m)
|
||||
if (!range) return res.status(400).json({ code: 40001, message: '月份格式无效' })
|
||||
@@ -79,13 +83,16 @@ router.get('/category', async (req: AuthRequest, res: Response) => {
|
||||
router.get('/trend', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { month, type = 'expense' } = req.query
|
||||
if (!VALID_TYPES.includes(type as string)) {
|
||||
return res.status(400).json({ code: 40002, message: '类型无效' })
|
||||
}
|
||||
const m = (month as string) || getCurrentMonth()
|
||||
const range = getMonthRange(m)
|
||||
if (!range) return res.status(400).json({ code: 40001, message: '月份格式无效' })
|
||||
const { startDate, endDate } = range
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT date, SUM(amount) as amount
|
||||
`SELECT DATE_FORMAT(date, '%Y-%m-%d') as date, SUM(amount) as amount
|
||||
FROM transactions
|
||||
WHERE user_id = ? AND type = ? AND date >= ? AND date <= ?
|
||||
GROUP BY date
|
||||
|
||||
@@ -16,7 +16,8 @@ function safeInt(val: any, fallback: number, min: number, max: number): number {
|
||||
router.get('/:id', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT t.*, c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
`SELECT t.id, t.user_id, t.amount, t.type, t.category_id, t.note, DATE_FORMAT(t.date, '%Y-%m-%d') as date, t.created_at, t.updated_at,
|
||||
c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE t.id = ? AND t.user_id = ?`,
|
||||
@@ -56,7 +57,8 @@ router.get('/', async (req: AuthRequest, res: Response) => {
|
||||
const orderBy = sortBy === 'amount' ? 't.amount DESC' : 't.date DESC, t.created_at DESC'
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT t.*, c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
`SELECT t.id, t.user_id, t.amount, t.type, t.category_id, t.note, DATE_FORMAT(t.date, '%Y-%m-%d') as date, t.created_at, t.updated_at,
|
||||
c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
${where}
|
||||
|
||||
100
server/src/utils/backup.ts
Normal file
100
server/src/utils/backup.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import zlib from 'zlib'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const gzipAsync = promisify(zlib.gzip)
|
||||
|
||||
const BACKUP_DIR = process.env.BACKUP_DIR || '/var/backups/xiaocai'
|
||||
const MAX_BACKUPS = 7 // 保留最近 7 天的备份
|
||||
|
||||
/**
|
||||
* 执行数据库备份
|
||||
* @returns 备份文件路径
|
||||
*/
|
||||
export async function backupDatabase(): Promise<string> {
|
||||
// 确保备份目录存在
|
||||
if (!fs.existsSync(BACKUP_DIR)) {
|
||||
fs.mkdirSync(BACKUP_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const date = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
|
||||
const filename = `xiaocai_${date}.sql.gz`
|
||||
const filepath = path.join(BACKUP_DIR, filename)
|
||||
|
||||
const dbHost = process.env.DB_HOST || 'localhost'
|
||||
const dbUser = process.env.DB_USER || 'root'
|
||||
const dbPassword = process.env.DB_PASSWORD || ''
|
||||
const dbName = process.env.DB_NAME || 'xiaocai'
|
||||
|
||||
try {
|
||||
// 使用 execFile 避免命令注入,参数通过数组传递
|
||||
const args = [
|
||||
`-h${dbHost}`,
|
||||
`-u${dbUser}`,
|
||||
...(dbPassword ? [`-p${dbPassword}`] : []),
|
||||
dbName
|
||||
]
|
||||
|
||||
const { stdout } = await execFileAsync('mysqldump', args, { maxBuffer: 50 * 1024 * 1024 })
|
||||
|
||||
// 使用 Node.js zlib 压缩
|
||||
const compressed = await gzipAsync(Buffer.from(stdout, 'utf-8'))
|
||||
fs.writeFileSync(filepath, compressed)
|
||||
|
||||
console.log(`[Backup] 完成: ${filename}`)
|
||||
|
||||
// 清理旧备份
|
||||
await cleanOldBackups()
|
||||
|
||||
return filepath
|
||||
} catch (err) {
|
||||
console.error('[Backup] 失败:', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期的备份文件
|
||||
*/
|
||||
async function cleanOldBackups(): Promise<void> {
|
||||
try {
|
||||
if (!fs.existsSync(BACKUP_DIR)) return
|
||||
|
||||
const files = fs.readdirSync(BACKUP_DIR)
|
||||
.filter(f => f.startsWith('xiaocai_') && (f.endsWith('.sql.gz') || f.endsWith('.sql')))
|
||||
.sort()
|
||||
.reverse()
|
||||
|
||||
// 删除超出保留数量的文件
|
||||
for (let i = MAX_BACKUPS; i < files.length; i++) {
|
||||
const filepath = path.join(BACKUP_DIR, files[i])
|
||||
fs.unlinkSync(filepath)
|
||||
console.log(`[Backup] 清理旧备份: ${files[i]}`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Backup] 清理失败:', err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取备份列表
|
||||
*/
|
||||
export function getBackupList(): Array<{ name: string; size: number; date: string }> {
|
||||
if (!fs.existsSync(BACKUP_DIR)) return []
|
||||
|
||||
return fs.readdirSync(BACKUP_DIR)
|
||||
.filter(f => f.startsWith('xiaocai_') && (f.endsWith('.sql.gz') || f.endsWith('.sql')))
|
||||
.map(f => {
|
||||
const filepath = path.join(BACKUP_DIR, f)
|
||||
const stats = fs.statSync(filepath)
|
||||
return {
|
||||
name: f,
|
||||
size: stats.size,
|
||||
date: stats.mtime.toISOString()
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b.date.localeCompare(a.date))
|
||||
}
|
||||
Reference in New Issue
Block a user