MIRROR/src/app/api/weather/route.ts
LIRUI f5dc9a4843
Some checks failed
部署 Next.js 站点到 Gitea / deploy (push) Failing after 10m5s
0228.4
2025-02-28 22:04:13 +08:00

67 lines
2.4 KiB
TypeScript

import { NextResponse } from 'next/server';
export async function GET() {
const apiKey = process.env.CAIYUN_API_KEY;
// 请替换为你的实际坐标(示例使用北京坐标)
const apiUrl = `https://api.caiyunapp.com/v2.6/${apiKey}/116.3974,39.9093/weather?alert=true&dailysteps=5`;
try {
const response = await fetch(apiUrl, { next: { revalidate: 600 } });
const data = await response.json();
// 数据格式转换
const formattedData = {
temp: Math.round(data.result.realtime.temperature),
feelsLike: Math.round(data.result.realtime.apparent_temperature),
condition: translateSkycon(data.result.realtime.skycon),
sunrise: data.result.daily.astro[0].sunrise.time,
sunset: data.result.daily.astro[0].sunset.time,
windSpeed: (data.result.realtime.wind.speed * 3.6).toFixed(1), // 转换为km/h
windDirection: getWindDirection(data.result.realtime.wind.direction),
uvIndex: data.result.realtime.life_index.ultraviolet.desc,
forecast: data.result.daily.temperature.map((item: any, index: number) => ({
day: formatDailyDate(item.date),
low: Math.round(item.min),
high: Math.round(item.max),
condition: translateSkycon(data.result.daily.skycon[index].value)
}))
};
return NextResponse.json(formattedData);
} catch (error) {
return NextResponse.json(
{ error: "天气数据获取失败" },
{ status: 500 }
);
}
}
// 天气状况翻译
function translateSkycon(skycon: string) {
const skyconMap: Record<string, string> = {
"CLEAR_DAY": "晴",
"CLEAR_NIGHT": "晴",
"PARTLY_CLOUDY_DAY": "多云",
"PARTLY_CLOUDY_NIGHT": "多云",
"CLOUDY": "阴",
"LIGHT_RAIN": "小雨",
"MODERATE_RAIN": "中雨",
"HEAVY_RAIN": "大雨",
"STORM_RAIN": "暴雨",
// 其他天气代码可继续补充...
};
return skyconMap[skycon] || skycon;
}
// 风向转换
function getWindDirection(degree: number) {
const directions = ["北风", "东北风", "东风", "东南风", "南风", "西南风", "西风", "西北风"];
return directions[Math.round(degree % 360 / 45) % 8];
}
// 日期格式化
function formatDailyDate(dateStr: string) {
const date = new Date(dateStr);
const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
return weekdays[date.getDay()];
}