1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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 {
// Fetch the points data to get the forecast endpoint
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;
// Fetch the actual 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";
// TODO throw error if missing lat/lng isntead of using Stowe VT
// don't really need names either
// would be nice to convert name to lat/lng
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 });
};