perf: Parallelize external API calls in weather route to reduce latency

This commit is contained in:
kihong.kim
2026-01-31 22:33:46 +09:00
parent e2f00c6e21
commit 7ddd29dfed

View File

@@ -18,27 +18,32 @@ router.get("/", async (req, res) => {
lang: language, lang: language,
}; };
let currentResponse, forecastResponse, airResponse;
if (lat && lon) { if (lat && lon) {
params.lat = lat; // 1. Parallel fetch for all 3 endpoints if coordinates are available
params.lon = lon; [currentResponse, forecastResponse, airResponse] = await Promise.all([
axios.get(`${baseUrl}/weather`, { params: { ...params, lat, lon } }),
axios.get(`${baseUrl}/forecast`, { params: { ...params, lat, lon } }),
axios.get(`${baseUrl}/air_pollution`, { params: { lat, lon, appid: apiKey } }),
]);
} else { } else {
// 2. Sequential fallback if only city name is provided
params.q = q || city; params.q = q || city;
currentResponse = await axios.get(`${baseUrl}/weather`, { params });
const { coord } = currentResponse.data;
[forecastResponse, airResponse] = await Promise.all([
axios.get(`${baseUrl}/forecast`, {
params: { ...params, lat: coord.lat, lon: coord.lon },
}),
axios.get(`${baseUrl}/air_pollution`, {
params: { lat: coord.lat, lon: coord.lon, appid: apiKey },
}),
]);
} }
// 1. Fetch Current Weather (to get lat/lon and timezone)
const currentResponse = await axios.get(`${baseUrl}/weather`, { params });
const currentData = currentResponse.data; const currentData = currentResponse.data;
const { coord } = currentData;
// 2. Fetch Forecast (for daily min/max) & Air Quality
const [forecastResponse, airResponse] = await Promise.all([
axios.get(`${baseUrl}/forecast`, {
params: { ...params, lat: coord.lat, lon: coord.lon },
}),
axios.get(`${baseUrl}/air_pollution`, {
params: { lat: coord.lat, lon: coord.lon, appid: apiKey },
}),
]);
// 3. Process Forecast for Today's Min/Max (Seoul Time: UTC+9) // 3. Process Forecast for Today's Min/Max (Seoul Time: UTC+9)
// OpenWeatherMap returns timestamps in UTC. // OpenWeatherMap returns timestamps in UTC.