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