47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import type { RadioStation } from './radioTypes.js';
|
|
|
|
const STATION_SYNC_CACHE_PREFIX = 'radioplayer-station-sync-';
|
|
|
|
async function loadSyncedCatalogFromCache(catalogUrl: string): Promise<Response | null> {
|
|
if (typeof window === 'undefined' || !('caches' in window)) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const cacheKeys = await caches.keys();
|
|
const syncCacheName = cacheKeys.find((cacheName) => cacheName.startsWith(STATION_SYNC_CACHE_PREFIX));
|
|
if (!syncCacheName) {
|
|
return null;
|
|
}
|
|
|
|
const syncCache = await caches.open(syncCacheName);
|
|
return await syncCache.match(catalogUrl) ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function loadRadioStations(): Promise<RadioStation[]> {
|
|
const syncedCatalogUrl = `${import.meta.env.BASE_URL}data/radio-stations-sync.json`;
|
|
const bundledCatalogUrl = `${import.meta.env.BASE_URL}data/radio-stations.json`;
|
|
const hasServiceWorkerController = typeof navigator !== 'undefined'
|
|
&& 'serviceWorker' in navigator
|
|
&& Boolean(navigator.serviceWorker.controller);
|
|
|
|
let response = null;
|
|
|
|
if (hasServiceWorkerController) {
|
|
response = await loadSyncedCatalogFromCache(syncedCatalogUrl);
|
|
}
|
|
|
|
if (!response?.ok) {
|
|
response = await fetch(bundledCatalogUrl);
|
|
}
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to load radio stations: ${response.status}`);
|
|
}
|
|
|
|
const stations = (await response.json()) as RadioStation[];
|
|
return Array.isArray(stations) ? stations : [];
|
|
} |