38 lines
1.4 KiB
TypeScript
38 lines
1.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { fetchServerCurrentWeather } from "@/lib/server-current-weather";
|
|
import type { WeatherRegion } from "@/types/weather-region";
|
|
|
|
function parseCoordinate(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;
|
|
}
|
|
|
|
function parseRegion(value: string | null): WeatherRegion {
|
|
return value === "GLOBAL" ? "GLOBAL" : "PL";
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
const { searchParams } = new URL(request.url);
|
|
const latitude = parseCoordinate(searchParams.get("latitude"), -90, 90);
|
|
const longitude = parseCoordinate(searchParams.get("longitude"), -180, 180);
|
|
const region = parseRegion(searchParams.get("region"));
|
|
if (latitude === null || longitude === null) {
|
|
return NextResponse.json({ error: "Invalid coordinates." }, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
return NextResponse.json(await fetchServerCurrentWeather(latitude, longitude, region), {
|
|
headers: { "Cache-Control": "public, s-maxage=120, stale-while-revalidate=300" },
|
|
});
|
|
} catch {
|
|
return NextResponse.json(
|
|
{
|
|
error:
|
|
region === "PL" ? "IMGW Hybrid service is unavailable." : "Open-Meteo current conditions are unavailable.",
|
|
},
|
|
{ status: 502 },
|
|
);
|
|
}
|
|
}
|