82 lines
1.8 KiB
JavaScript
82 lines
1.8 KiB
JavaScript
import { createPool } from 'mariadb';
|
|
|
|
async function handler(req, res) {
|
|
if (req.method !== 'GET') {
|
|
return res.status(405).json({ message: '只支持GET请求' });
|
|
}
|
|
|
|
const { startDate, endDate, limit } = req.query;
|
|
|
|
let pool;
|
|
try {
|
|
pool = createPool({
|
|
host: process.env.DB_HOST || '192.168.111.111',
|
|
port: parseInt(process.env.DB_PORT || '3306'),
|
|
user: process.env.DB_USER || 'root',
|
|
password: process.env.DB_PASSWORD || 'fullstack',
|
|
database: process.env.DB_NAME || 'iboard',
|
|
connectionLimit: 5
|
|
});
|
|
|
|
let query = 'SELECT date, close FROM econ_SH300Index';
|
|
const params = [];
|
|
const conditions = [];
|
|
|
|
if (startDate) {
|
|
conditions.push('date >= ?');
|
|
params.push(startDate);
|
|
}
|
|
|
|
if (endDate) {
|
|
conditions.push('date <= ?');
|
|
params.push(endDate);
|
|
}
|
|
|
|
if (conditions.length > 0) {
|
|
query += ' WHERE ' + conditions.join(' AND ');
|
|
}
|
|
|
|
query += ' ORDER BY date ASC';
|
|
|
|
if (limit) {
|
|
query += ' LIMIT ?';
|
|
params.push(parseInt(limit));
|
|
}
|
|
|
|
const result = await pool.query(query, params);
|
|
|
|
const data = result.map(row => {
|
|
let dateStr;
|
|
if (row.date instanceof Date) {
|
|
dateStr = row.date.toISOString().split('T')[0];
|
|
} else if (typeof row.date === 'string') {
|
|
dateStr = row.date;
|
|
} else {
|
|
dateStr = String(row.date);
|
|
}
|
|
return {
|
|
date: dateStr,
|
|
close: parseFloat(row.close)
|
|
};
|
|
});
|
|
|
|
return res.status(200).json({
|
|
success: true,
|
|
data: data
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('获取沪深300数据失败:', error);
|
|
return res.status(500).json({
|
|
success: false,
|
|
message: '获取沪深300数据失败: ' + error.message
|
|
});
|
|
} finally {
|
|
if (pool) {
|
|
await pool.end();
|
|
}
|
|
}
|
|
}
|
|
|
|
export default handler;
|