diff --git a/packages/beeq/src/components/icon/helper/request.ts b/packages/beeq/src/components/icon/helper/request.ts index e863ad298..93e0579eb 100644 --- a/packages/beeq/src/components/icon/helper/request.ts +++ b/packages/beeq/src/components/icon/helper/request.ts @@ -2,38 +2,44 @@ /* Icon request helper */ /* -------------------------------------------------------------------------- */ -import { isString } from '../../../shared/utils'; +import { isNil, isString } from '../../../shared/utils'; const requests = new Map>(); const fetchSvg = async (url: string, sanitize: boolean): Promise => { - let req: Promise; - - if (typeof fetch !== 'undefined' && typeof document !== 'undefined') { - const rsp = await fetch(url); - if (rsp.ok) { - return rsp.text().then((svgContent) => { - if (svgContent && sanitize !== false) svgContent = validateContent(svgContent); - iconContent.set(url, svgContent || ''); - }); + if (typeof fetch === 'undefined' || typeof document === 'undefined') return; + + if (requests.has(url)) return requests.get(url); + + try { + const response = await fetch(url); + + if (!response.ok) { + iconContent.set(url, ''); + return; } + + let svgContent = (await response.text()) || ''; + + if (svgContent && sanitize !== false) svgContent = validateContent(svgContent); + + iconContent.set(url, svgContent); + } catch (error) { + console.error(`[BqIcon] Failed to fetch SVG from ${url}:`, error); iconContent.set(url, ''); - // cache for the same requests - requests.set(url, req); - return req; } - - iconContent.set(url, ''); - return Promise.resolve(); }; export const iconContent = new Map(); export const getSvgContent = async (url: string, sanitize: boolean) => { - // see if we already have a request for this SVG file - const req = await requests.get(url); - if (!req) return fetchSvg(url, sanitize); + let req = requests.get(url); + // NOTE: if the request does not exists we will cache it + if (isNil(req)) { + req = fetchSvg(url, sanitize); + requests.set(url, req); + } return req; };