UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

123 lines 3.04 kB
import { COUNTRY as defaultCountry } from "../../../shared/defaults.js"; export function createContext(generalConfig = null) { return { withConfig(fn, handlerConfig) { return fn(generalConfig, handlerConfig); } }; } async function fetchDataFromAPI(generalConfig, options) { const { fetchConfig } = generalConfig; const controller = options?.abortControllerRef; if (controller) { if (controller.current) { controller.current.abort(); controller.current = null; } if (!controller.current) { controller.current = new AbortController(); } } const { signal } = controller?.current || {}; const fetchOptions = { method: 'GET', headers: { Accept: 'application/json', ...fetchConfig.headers }, signal }; try { const response = await fetch(fetchConfig.url, fetchOptions); if (controller) { controller.current = null; } return { response, data: await response.json() }; } catch (error) { if (error.name !== 'AbortError') { return error; } } } export async function fetchData(value, options) { const { generalConfig, parameters } = options || {}; const result = options?.preResponseResolver?.({ value }); if (typeof result !== 'undefined') { return result; } const u = generalConfig.fetchConfig.url; const url = typeof u === 'function' ? await u(value, parameters) : u; const { data, response } = await fetchDataFromAPI({ ...generalConfig, fetchConfig: { ...generalConfig.fetchConfig, url } }, options); if (!response) { throw new Error('Please try again!'); } if (!response.ok) { throw new Error(`${response.statusText} – Status: ${response.status}`); } return { data, status: response.status }; } export function getCountryCodeValue({ countryCode: givenCountryCode, additionalArgs }) { const countryCodeValue = givenCountryCode || additionalArgs.props?.['data-country-code'] || defaultCountry; const countryCode = additionalArgs.getSourceValue(countryCodeValue) || givenCountryCode; return { countryCode, countryCodeValue }; } export function handleCountryPath({ value, countryCode: givenCountryCode, additionalArgs, handler }) { const { countryCode, countryCodeValue } = getCountryCodeValue({ countryCode: givenCountryCode || additionalArgs.props?.['data-country-code'], additionalArgs }); if (String(countryCodeValue).startsWith('/') && additionalArgs[handler.name] !== handler) { additionalArgs[handler.name] = handler; additionalArgs.setFieldEventListener(countryCodeValue, 'onPathChange', () => { handler(value, additionalArgs); }); } return { countryCode }; } export function isSupportedCountryCode(countryCode, supportedCountryCodes) { if (!countryCode) { return false; } return supportedCountryCodes.includes(String(countryCode).toUpperCase()); } //# sourceMappingURL=createContext.js.map