sozday-dlya-menya-prilozheni/environment.js

48 lines
2.6 KiB
JavaScript

/* Живой прогноз Open-Meteo: Астана. Кэш снижает число внешних запросов. */
const WEATHER_URL = "https://api.open-meteo.com/v1/forecast?latitude=51.1694&longitude=71.4491&current=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,temperature_2m_min,uv_index_max&timezone=Asia%2FAlmaty&forecast_days=7";
const AIR_URL = "https://air-quality-api.open-meteo.com/v1/air-quality?latitude=51.1694&longitude=71.4491&current=european_aqi,pm2_5&timezone=Asia%2FAlmaty";
let cache = null;
let pending = null;
async function fetchJson(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const response = await fetch(url, {signal:controller.signal, headers:{"User-Agent":"AuadaPersonalApp/1.0"}});
if (!response.ok) throw new Error("Open-Meteo HTTP " + response.status);
return await response.json();
} finally { clearTimeout(timer); }
}
function normalize(raw, air) {
if (!raw || !raw.current || !Array.isArray(raw.daily && raw.daily.time)) throw new Error("Некорректный ответ прогноза");
return {
temp:Math.round(raw.current.temperature_2m), feels:Math.round(raw.current.apparent_temperature),
humidity:Math.round(raw.current.relative_humidity_2m), wind:Math.round(raw.current.wind_speed_10m*10)/10,
code:raw.current.weather_code, updated:raw.current.time,
aqi:air && air.current && Number.isFinite(air.current.european_aqi) ? Math.round(air.current.european_aqi) : null,
pm25:air && air.current ? air.current.pm2_5 : null, isDemo:false,
daily:raw.daily.time.map((date,i)=>({date,min:Math.round(raw.daily.temperature_2m_min[i]),max:Math.round(raw.daily.temperature_2m_max[i]),uv:Math.round(raw.daily.uv_index_max[i]*10)/10,code:raw.daily.weather_code[i]}))
};
}
async function updateEnvironment() {
const [weather,air] = await Promise.allSettled([fetchJson(WEATHER_URL),fetchJson(AIR_URL)]);
if (weather.status !== "fulfilled") throw new Error("Сервис прогноза недоступен");
cache = {data:normalize(weather.value,air.status === "fulfilled" ? air.value : null),time:Date.now(),stale:false};
return cache;
}
async function getEnvironment() {
if (cache && Date.now()-cache.time < 15*60*1000) return cache;
if (pending) return pending;
pending = updateEnvironment();
try { return await pending; }
catch (error) {
if (cache) return {...cache,stale:true};
throw error;
} finally { pending = null; }
}
module.exports = {getEnvironment};