import {ref, onUnmounted} from 'vue'; export type DataRow = Record export const BASE = import.meta.env.DEV ? 'http://10.69.5.23' : ''; const cache: any = {}; const current = ref(null); const hourly = ref([]); const daily = ref([]); let interval: ReturnType; let refCount = 0; async function get(path: string, params: Record = {}): Promise { const url = new URL(`${BASE}${path}`, window.location.origin); Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v)); const key = url.toString(); if(cache[key]) return cache[key]; cache[key] = fetch(url.toString()) .then(resp => resp.json()) .finally(() => delete cache[key]); return cache[key]; } export const api = { position: (fields?: string) => get<{latitude: number, longitude: number, altitude: number}>('/api/position', fields ? {fields} : {}), current: (fields?: string) => get('/api/current', fields ? {fields} : {}), hourly: (start?: Date | string, end?: Date | string, fields?: string) => get('/api/hourly', { ...(start ? {start: typeof start == 'string' ? start : start.toISOString()} : {}), ...(end ? {end: typeof end == 'string' ? end : end.toISOString()} : {}), ...(fields ? {fields} : {}) }), daily: (start?: Date, end?: Date, fields?: string) => get('/api/daily', { ...(start ? {start: typeof start == 'string' ? start : start.toISOString()} : {}), ...(end ? {end: typeof end == 'string' ? end : end.toISOString()} : {}), ...(fields ? {fields} : {}) }), }; async function refresh() { const start = new Date(), end = new Date(); start.setDate(start.getDate() + 1); end.setDate(end.getDate() + 5); current.value = await api.current(); return {current} } export function useWeather(ms = 5 * 60_000) { if(++refCount === 1) { refresh(); interval = setInterval(refresh, ms); } onUnmounted(() => { if(--refCount === 0) clearInterval(interval); }); return {current, hourly, daily, refresh}; }