perf: Parallelize external API calls in weather route to reduce latency
This commit is contained in:
@@ -18,20 +18,22 @@ 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;
|
||||||
|
|
||||||
// 1. Fetch Current Weather (to get lat/lon and timezone)
|
[forecastResponse, airResponse] = await Promise.all([
|
||||||
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([
|
|
||||||
axios.get(`${baseUrl}/forecast`, {
|
axios.get(`${baseUrl}/forecast`, {
|
||||||
params: { ...params, lat: coord.lat, lon: coord.lon },
|
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 },
|
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)
|
// 3. Process Forecast for Today's Min/Max (Seoul Time: UTC+9)
|
||||||
// OpenWeatherMap returns timestamps in UTC.
|
// OpenWeatherMap returns timestamps in UTC.
|
||||||
|
|||||||
Reference in New Issue
Block a user