Files
wtr/lib/server-forecast.ts
zv 2182297adc
All checks were successful
CI / Lint, typecheck and build (push) Successful in 9m54s
feat: add global weather support
2026-06-14 15:59:14 +02:00

56 lines
2.4 KiB
TypeScript

import { mergeForecastSources } from "@/lib/forecast-merge";
import type { RawImgwForecastResponse, RawWeatherForecast } from "@/types/forecast";
import type { WeatherRegion } from "@/types/weather-region";
const OPEN_METEO_FORECAST_URL = "https://api.open-meteo.com/v1/forecast";
const IMGW_FORECAST_URL = "https://meteo.imgw.pl/api/v1/forecast/fcapi";
// This browser token is published by the official meteo.imgw.pl frontend.
const IMGW_FORECAST_TOKEN = "p4DXKjsYadfBV21TYrDk";
const OPEN_METEO_TIMEOUT_MS = 12_000;
const IMGW_TIMEOUT_MS = 5_000;
export function parseForecastCoordinate(value: string | null, min: number, max: number) {
if (!value?.trim()) return null;
const coordinate = Number(value);
return Number.isFinite(coordinate) && coordinate >= min && coordinate <= max ? coordinate : null;
}
async function readImgwPayload(response: Response | null) {
if (!response?.ok) return null;
try {
return await response.json() as RawImgwForecastResponse;
} catch {
return null;
}
}
export async function fetchServerForecast(latitude: number, longitude: number, region: WeatherRegion = "PL") {
const openMeteoParams = new URLSearchParams({
latitude: String(latitude),
longitude: String(longitude),
hourly: "temperature_2m,apparent_temperature,precipitation_probability,precipitation,weather_code,wind_speed_10m",
daily: "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,precipitation_sum,sunrise,sunset",
timezone: region === "PL" ? "Europe/Warsaw" : "auto",
forecast_days: "7",
wind_speed_unit: "ms",
});
const imgwParams = new URLSearchParams({
token: IMGW_FORECAST_TOKEN,
lat: String(latitude),
lon: String(longitude),
m: "alaro",
});
const [openMeteoResponse, imgwResponse] = await Promise.all([
fetch(`${OPEN_METEO_FORECAST_URL}?${openMeteoParams}`, { next: { revalidate: 900 }, signal: AbortSignal.timeout(OPEN_METEO_TIMEOUT_MS) }),
region === "PL"
? fetch(`${IMGW_FORECAST_URL}?${imgwParams}`, { next: { revalidate: 900 }, signal: AbortSignal.timeout(IMGW_TIMEOUT_MS) }).catch(() => null)
: Promise.resolve(null),
]);
if (!openMeteoResponse.ok) throw new Error("Forecast service is unavailable.");
const openMeteoPayload = await openMeteoResponse.json() as RawWeatherForecast;
const imgwPayload = await readImgwPayload(imgwResponse);
return mergeForecastSources(openMeteoPayload, imgwPayload, region);
}