perf: Parallelize external API calls in weather route to reduce latency
This commit is contained in:
@@ -18,27 +18,32 @@ 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;
|
||||
|
||||
[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 { 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)
|
||||
// OpenWeatherMap returns timestamps in UTC.
|
||||
|
||||
Reference in New Issue
Block a user