88 lines
3.1 KiB
JavaScript
88 lines
3.1 KiB
JavaScript
const express = require('express');
|
|
const db = require('../db-sqlite');
|
|
const { authenticate } = require('../middleware/auth');
|
|
|
|
module.exports = function(app) {
|
|
const router = express.Router();
|
|
|
|
router.get('/latest', authenticate, async (req, res) => {
|
|
try {
|
|
const latestRateResult = await db.query('SELECT currency, rate, updated_at FROM exchange_rates ORDER BY updated_at DESC LIMIT 1');
|
|
const latestRate = latestRateResult.rows[0];
|
|
res.json({ success: true, data: latestRate });
|
|
} catch (error) {
|
|
console.error('获取最新汇率失败:', error);
|
|
res.status(500).json({ success: false, message: '获取最新汇率失败' });
|
|
}
|
|
});
|
|
|
|
router.get('/', authenticate, async (req, res) => {
|
|
try {
|
|
const ratesResult = await db.query('SELECT id, currency, rate, updated_at FROM exchange_rates ORDER BY updated_at DESC');
|
|
const rates = ratesResult.rows;
|
|
res.json({ success: true, data: rates, count: rates.length });
|
|
} catch (error) {
|
|
console.error('获取汇率列表失败:', error);
|
|
res.status(500).json({ success: false, message: '获取汇率列表失败' });
|
|
}
|
|
});
|
|
|
|
router.get('/history', authenticate, async (req, res) => {
|
|
try {
|
|
const { currency, startDate, endDate } = req.query;
|
|
let query = 'SELECT id, currency, rate, updated_at FROM exchange_rates';
|
|
const params = [];
|
|
|
|
if (currency) {
|
|
query += ' WHERE currency = ?';
|
|
params.push(currency);
|
|
}
|
|
|
|
if (startDate) {
|
|
query += (params.length > 0 ? ' AND' : ' WHERE') + ' updated_at >= ?';
|
|
params.push(startDate);
|
|
}
|
|
|
|
if (endDate) {
|
|
query query += ' AND updated_at <= ?';
|
|
params.push(endDate);
|
|
}
|
|
|
|
query += ' ORDER BY updated_at DESC';
|
|
|
|
const historyResult = await db.query(query, params);
|
|
const history = historyResult.rows;
|
|
res.json({ success: true, data: history, count: history.length });
|
|
} catch (error) {
|
|
console.error('获取汇率历史失败:', error);
|
|
res.status(500).json({ success: false, message: '获取汇率历史失败' });
|
|
}
|
|
});
|
|
|
|
router.post('/', authenticate, async (req, res) => {
|
|
try {
|
|
const { currency, rate } = req.body;
|
|
|
|
if (!currency || !rate) {
|
|
return res.status(400).json({ success: false, message: '货币和汇率为必填项' });
|
|
}
|
|
|
|
const result = await db.query(
|
|
'INSERT INTO exchange_rates (currency, rate, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)',
|
|
[currency, rate]
|
|
);
|
|
|
|
const newRateResult = await db.query('SELECT id, currency, rate, updated_at FROM exchange_rates WHERE id = ?', [result.lastID]);
|
|
const newRate = newRateResult.rows[0];
|
|
|
|
console.log(`汇率 ${currency} = ${rate} 更新成功,由 ${req.user.username} 操作`);
|
|
res.json({ success: true, data: newRate });
|
|
} catch (error) {
|
|
console.error('更新汇率失败:', error);
|
|
res.status(500).json({ success: false, message: '更新汇率失败' });
|
|
}
|
|
});
|
|
|
|
app.use('/api/exchange-rates', router);
|
|
};
|