import { fetch } from "https://esm.town/v/std/fetch";
export const fetchWeatherPrediction = async (req: Request) => {
interface Forecast {
startTime: string;
endTime: string;
temperature: number;
temperatureUnit: string;
shortForecast: string;
}
interface WeatherApiResponse {
properties: {
periods: Forecast[];
};
}
async function fetchForecast(
latitude: number,
longitude: number,
): Promise<Forecast[]> {
try {
const pointsUrl: string =
`https://api.weather.gov/points/${latitude},${longitude}`;
console.log(pointsUrl);
const pointsResponse = await fetch(pointsUrl, {
headers: { "Accept": "application/geo+json" },
});
console.log(pointsResponse);
const pointsData = await pointsResponse.json();
const forecastUrl: string = pointsData.properties.forecast;
const forecastResponse = await fetch(forecastUrl, {
headers: { "Accept": "application/geo+json" },
});
const forecastData: WeatherApiResponse = await forecastResponse.json();
console.log({ forecastData });
return forecastData.properties.periods;
}
catch (error) {
console.error(error);
throw error;
}
}
const params = new URL(req.url).searchParams;
const lat = parseFloat(
params.get("lat") ?? params.get("latitude") ?? "44.4654",
);
const lng = parseFloat(
params.get("lng") ?? params.get("long") ?? params.get("longitude") ??
"-72.6874",
);
const placeName = params.get("name") ?? "Stowe, VT";
const forecast = await fetchForecast(lat, lng);
console.log(`Forecast for ${placeName} @ ${lat},${lng}`);
forecast.forEach((period) => {
console.log(
`${period.startTime} to ${period.endTime}: ${period.shortForecast}, ${period.temperature} ${period.temperatureUnit}`,
);
});
return Response.json({ forecast });
};