jamiedubs-weatherincity.web.val.run
Readme

get weather forecast for a city. pass ?city=Cleveland,OH. e.g.: https://jamiedubs-weatherInCity.web.val.run/?city=brooklyn,ny

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
export const getWeatherForecast = async (req: Request) => {
const url = new URL(req.url);
const city = url.searchParams.get("city");
if (!city) {
return new Response("City parameter is required", {
status: 400, // Bad Request
headers: { "Content-Type": "text/plain" },
});
}
const weatherApiUrl = `https://wttr.in/${encodeURIComponent(city)}?format=j1`;
try {
const weatherResponse = await fetch(weatherApiUrl);
if (!weatherResponse.ok) {
throw new Error(`Weather API request failed with status: ${weatherResponse.status}`);
}
const weatherData = await weatherResponse.json();
const currentTempC = weatherData.current_condition[0].temp_C;
const currentTempF = weatherData.current_condition[0].temp_F;
const forecast = weatherData.weather[0].hourly.slice(0, 8).map(hour => ({
time: hour.time,
tempC: hour.tempC,
tempF: hour.tempF,
desc: hour.weatherDesc[0].value,
}));
const forecastString = forecast.reduce((acc, hour) => {
return `${acc}Time: ${hour.time}, Temp: ${hour.tempC}°C/${hour.tempF}°F, Description: ${hour.desc}\n`;
}, `Current Temperature: ${currentTempC}°C/${currentTempF}°F\nForecast for the next 8 hours:\n`);
return new Response(forecastString, {
status: 200, // OK
headers: { "Content-Type": "text/plain" },
});
} catch (err) {
return new Response("Error fetching weather data: " + err.message, {
status: 500, // Internal Server Error
headers: { "Content-Type": "text/plain" },
});
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
February 16, 2024