iboard/pages/api/sh300-index.js
2026-04-26 11:41:39 +08:00

79 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 && endDate) {
conditions.push('date BETWEEN ? AND ?');
params.push(startDate, endDate);
}
if (conditions.length > 0) {
query += ' WHERE ' + conditions.join(' AND ');
}
query += ' ORDER BY date DESC';
const result = await pool.query(query, params);
// 限制返回数量默认为30
const limitValue = limit ? parseInt(limit) : 30;
const limitedResult = result.slice(0, limitValue);
// 反转顺序,使日期从早到晚
const sortedResult = limitedResult.reverse();
const data = sortedResult.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;