Files
DianZhanDemo/server/api/power-station/chart-data.get.ts

77 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-12-11 01:39:13 +08:00
/**
* API
* ID和图表类型获取应力或温度历史数据
*/
export default defineEventHandler(async (event) => {
try {
const query = getQuery(event)
// 获取必需参数
const nodeId = query.nodeId as string
const chartType = query.type as 'stress' | 'temp'
if (!nodeId) {
throw createError({
statusCode: 400,
statusMessage: '缺少必要参数: nodeId',
})
}
if (!chartType || !['stress', 'temp'].includes(chartType)) {
throw createError({
statusCode: 400,
statusMessage: '缺少必要参数: type (必须为 stress 或 temp)',
})
}
// 模拟数据生成(基于数据库结构)
// 实际项目中这里应该连接真实数据库查询
const dates = []
const values = []
const now = new Date()
// 生成最近30天的数据
for (let i = 0; i < 30; i++) {
const date = new Date(now.getTime() - (29 - i) * 24 * 60 * 60 * 1000)
dates.push(date.toISOString().split('T')[0])
if (chartType === 'stress') {
// 应力数据100-150 MPa模拟真实应力变化
const baseStress = 120 + Math.sin(i * 0.2) * 10
const randomVariation = (Math.random() - 0.5) * 20
values.push(Math.round((baseStress + randomVariation) * 10) / 10)
} else {
// 温度数据560-580°C模拟真实温度变化
const baseTemp = 570 + Math.sin(i * 0.15) * 5
const randomVariation = (Math.random() - 0.5) * 10
values.push(Math.round((baseTemp + randomVariation) * 10) / 10)
}
}
// 返回图表数据
const result = {
dates,
values,
unit: chartType === 'stress' ? 'MPa' : '°C',
name: chartType === 'stress' ? '历史应力 (Stress)' : '历史温度 (Temp)',
nodeId,
chartType,
}
return {
success: true,
data: result,
message: '成功获取图表数据',
timestamp: new Date().toISOString(),
}
} catch (error) {
console.error('获取图表数据失败:', error)
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.message || '获取图表数据失败',
})
}
})