Files
Wegwichtel/public/js/api-client.js
T
Florian Zumpe 8f4664282b
Sonarqube Scanner / Prepare environment (push) Successful in 14s
Sonarqube Scanner / Build and test (push) Successful in 22s
Sonarqube Scanner / SonarQube analysis (push) Failing after 1m14s
Sonarqube Scanner / Deploy to Server (push) Successful in 11s
add offline support
2026-09-30 23:27:42 +02:00

49 lines
1.7 KiB
JavaScript

(function (ns, $) {
'use strict';
async function offlineResponse(path) {
if (!ns.OfflineStore) return null;
if (path === '/health') {
const available = await ns.OfflineStore.state() || (await ns.OfflineStore.routes()).length;
return available ? { ok: true, offline: true } : null;
}
if (path.startsWith('/routes?')) {
if (!await ns.OfflineStore.state() && !(await ns.OfflineStore.routes()).length) return null;
return { routes: (await ns.OfflineStore.routes()).map(item => item.route), offline: true };
}
const response = await ns.OfflineStore.match(ns.Config.apiBase + path);
return response ? response.json() : null;
}
async function request(path) {
if (globalThis.navigator?.onLine === false) {
const response = await offlineResponse(path);
if (response) return response;
}
try {
return await $.ajax({ url: ns.Config.apiBase + path, method: 'GET', dataType: 'json', cache: false, timeout: 10000 });
} catch (error) {
if (error.status > 0) throw error;
const response = await offlineResponse(path);
if (response) return response;
throw error;
}
}
function routeQuery(position) {
const params = new URLSearchParams({ activatedOnly: 'true' });
if (position) {
params.set('lat', String(position.lat));
params.set('lon', String(position.lon));
params.set('radiusKm', String(ns.Config.routeRadiusKm));
}
return `/routes?${params.toString()}`;
}
ns.Api = {
health: () => request('/health'),
routes: position => request(routeQuery(position)),
route: id => request(`/routes/${encodeURIComponent(id)}`)
};
}(globalThis.Wegwichtel, globalThis.jQuery));