49 lines
1.7 KiB
JavaScript
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));
|