50 lines
1.4 KiB
JavaScript
50 lines
1.4 KiB
JavaScript
export function shouldLoadMobileFacilities({ isMobile, mobileActive, cardsEnabled }) {
|
|
return Boolean(isMobile && mobileActive && !cardsEnabled);
|
|
}
|
|
|
|
export function nextMobileRegionExpansion(currentCode, clickedCode) {
|
|
return currentCode === clickedCode ? null : clickedCode;
|
|
}
|
|
|
|
export function createMobileFacilitiesLoader({
|
|
endpoint = "/api/v1/data-products/compute/facilities",
|
|
fetchImpl = fetch,
|
|
} = {}) {
|
|
let controller = null;
|
|
let serial = 0;
|
|
|
|
function cancel() {
|
|
serial++;
|
|
controller?.abort();
|
|
controller = null;
|
|
}
|
|
|
|
async function load({ countries, year, onSuccess, onError }) {
|
|
cancel();
|
|
controller = new AbortController();
|
|
const requestController = controller;
|
|
const token = serial;
|
|
const params = new URLSearchParams({ countries: countries.join(",") });
|
|
if (year) params.set("year", year);
|
|
|
|
try {
|
|
const response = await fetchImpl(`${endpoint}?${params}`, {
|
|
signal: requestController.signal,
|
|
});
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
const payload = await response.json();
|
|
if (token !== serial) return { stale: true };
|
|
controller = null;
|
|
onSuccess?.(payload);
|
|
return { payload };
|
|
} catch (error) {
|
|
if (error.name === "AbortError" || token !== serial) return { stale: true };
|
|
controller = null;
|
|
onError?.(error);
|
|
return { error };
|
|
}
|
|
}
|
|
|
|
return { cancel, load };
|
|
}
|