JewelryMall/server/src/controllers/config.ts
2026-03-05 00:43:04 +08:00

60 lines
2.1 KiB
TypeScript

import { Request, Response } from 'express'
import pool from '../utils/db'
import { RowDataPacket } from 'mysql2'
// GET /api/config/:key - 公开获取配置
export async function getConfig(req: Request, res: Response): Promise<void> {
try {
const { key } = req.params
const [rows] = await pool.execute<RowDataPacket[]>(
'SELECT config_value FROM system_configs WHERE config_key = ?',
[key]
)
if (rows.length === 0) {
res.json({ code: 0, data: null })
return
}
let value = rows[0].config_value
try { value = JSON.parse(value) } catch { /* keep as string */ }
res.json({ code: 0, data: value })
} catch (err) {
console.error('getConfig error:', err)
res.status(500).json({ code: 500, message: '获取配置失败' })
}
}
// GET /api/admin/configs - 管理后台获取所有配置
export async function adminGetConfigs(_req: Request, res: Response): Promise<void> {
try {
const [rows] = await pool.execute<RowDataPacket[]>(
'SELECT id, config_key, config_value, updated_at FROM system_configs ORDER BY id ASC'
)
const data = rows.map((r: any) => {
let val = r.config_value
try { val = JSON.parse(val) } catch { /* keep */ }
return { ...r, config_value: val }
})
res.json({ code: 0, data })
} catch (err) {
console.error('adminGetConfigs error:', err)
res.status(500).json({ code: 500, message: '获取配置列表失败' })
}
}
// PUT /api/admin/configs/:key - 管理后台更新配置
export async function adminUpdateConfig(req: Request, res: Response): Promise<void> {
try {
const { key } = req.params
const { value } = req.body
const strValue = typeof value === 'string' ? value : JSON.stringify(value)
await pool.execute(
'INSERT INTO system_configs (config_key, config_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE config_value = ?',
[key, strValue, strValue]
)
res.json({ code: 0, message: '更新成功' })
} catch (err) {
console.error('adminUpdateConfig error:', err)
res.status(500).json({ code: 500, message: '更新配置失败' })
}
}