-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
176 lines (144 loc) · 7.15 KB
/
Copy pathapp.js
File metadata and controls
176 lines (144 loc) · 7.15 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// ─────────────────────────────────────────────────────────────
// Frontend logic for the WECS Weather App.
// ─────────────────────────────────────────────────────────────
// ── API base URL ──────────────────────────────────────────────
const API_BASE = window.location.hostname === "localhost"
? "http://localhost:3000"
: ""; // empty string = same domain, works on Vercel automatically
// ── Grab DOM elements we'll interact with ─────────────────────
const cityInput = document.getElementById("city-input");
const searchBtn = document.getElementById("search-btn");
const errorMsg = document.getElementById("error-msg");
const loading = document.getElementById("loading");
const results = document.getElementById("results");
// ── Event listeners ───────────────────────────────────────────
// Two ways to trigger a search: clicking the button or pressing Enter
searchBtn.addEventListener("click", handleSearch);
cityInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") handleSearch();
});
// ── Main search handler ───────────────────────────────────────
async function handleSearch() {
const city = cityInput.value.trim();
// Don't run if the input is empty
if (!city) {
showError("Please enter a city name.");
return;
}
// Reset UI state before fetching
clearError();
showLoading(true);
hideResults();
try {
// ── Fetch all three endpoints in parallel ─────────────────
const [weatherData, forecastData, aqiData] = await Promise.all([
fetchJSON(`${API_BASE}/api/weather?city=${encodeURIComponent(city)}`),
fetchJSON(`${API_BASE}/api/forecast?city=${encodeURIComponent(city)}`),
fetchJSON(`${API_BASE}/api/airquality?city=${encodeURIComponent(city)}`),
]);
// Render each section
renderCurrentWeather(weatherData);
renderAirQuality(aqiData);
renderForecast(forecastData);
// Show the results section
showLoading(false);
showResults();
} catch (err) {
showLoading(false);
showError(err.message || "Something went wrong. Please try again.");
}
}
// ── fetchJSON helper ──────────────────────────────────────────
// Wraps fetch() with error handling so we get clean error
// messages from our API instead of generic network errors.
async function fetchJSON(url) {
const response = await fetch(url);
const data = await response.json();
// If our API returned an error status, throw with its message
if (!response.ok) {
throw new Error(data.error || `Request failed (${response.status})`);
}
return data;
}
// ── Render: current weather ───────────────────────────────────
function renderCurrentWeather(data) {
const { location, current, conditions, wind, atmosphere, sun } = data;
// Location
document.getElementById("city-name").textContent = location.city;
document.getElementById("city-country").textContent =
location.state ? `${location.state}, ${location.country}` : location.country;
// Icon
const icon = document.getElementById("weather-icon");
icon.src = conditions.icon_url;
icon.alt = conditions.description;
// Temperature & description
document.getElementById("current-temp").textContent = `${current.temp_c}°C`;
document.getElementById("current-desc").textContent = conditions.description;
// Detail pills
document.getElementById("feels-like").textContent = `${current.feels_like_c}°C`;
document.getElementById("humidity").textContent = `${current.humidity_percent}%`;
document.getElementById("wind").textContent = `${wind.speed_kph} km/h`;
document.getElementById("visibility").textContent =
atmosphere.visibility_km ? `${atmosphere.visibility_km} km` : "N/A";
// Sunrise/sunset — convert ISO string to local time
document.getElementById("sunrise").textContent = formatTime(sun.sunrise);
document.getElementById("sunset").textContent = formatTime(sun.sunset);
}
// ── Render: air quality ───────────────────────────────────────
function renderAirQuality(data) {
const { air_quality } = data;
const label = document.getElementById("aqi-label");
label.textContent = `${air_quality.label} (${air_quality.aqi}/5)`;
// Apply the color our API sent back directly to the element
label.style.color = air_quality.color;
label.style.border = `1px solid ${air_quality.color}`;
document.getElementById("aqi-advice").textContent = air_quality.advice;
}
// ── Render: 5-day forecast ────────────────────────────────────
function renderForecast(data) {
const strip = document.getElementById("forecast-strip");
// Clear any previous forecast before rendering new one
strip.innerHTML = "";
// Skip today (index 0) — we already show it in current weather
// Show the next 5 days
const days = data.forecast.slice(1, 6);
days.forEach(day => {
// Build a forecast card for each day using a template string
// This is injected as HTML — fine here since we control the data source
const card = document.createElement("div");
card.className = "forecast-day";
card.innerHTML = `
<span class="forecast-day-name">${day.day_of_week.slice(0, 3)}</span>
<img class="forecast-icon" src="${day.condition.icon_url}" alt="${day.condition.description}" />
<span class="forecast-high">${day.temp_high_c}°</span>
<span class="forecast-low">${day.temp_low_c}°</span>
`;
strip.appendChild(card);
});
}
// ── UI state helpers ──────────────────────────────────────────
function showError(message) {
errorMsg.textContent = message;
errorMsg.classList.remove("hidden");
}
function clearError() {
errorMsg.textContent = "";
errorMsg.classList.add("hidden");
}
function showLoading(show) {
loading.classList.toggle("hidden", !show);
}
function showResults() {
results.classList.remove("hidden");
}
function hideResults() {
results.classList.add("hidden");
}
// ── Utility: format ISO timestamp → "7:23 AM" ─────────────────
function formatTime(isoString) {
return new Date(isoString).toLocaleTimeString("en-US", {
hour: "numeric",
minute: "2-digit",
hour12: true,
});
}