Skip to content

Commit

Permalink
fix(Icon): dedupe icon requests (#1209)
Browse files Browse the repository at this point in the history
  • Loading branch information
endv-bogdanb authored Aug 6, 2024
1 parent a1d41fc commit 6da3a3f
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions packages/beeq/src/components/icon/helper/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,44 @@
/* Icon request helper */
/* -------------------------------------------------------------------------- */

import { isString } from '../../../shared/utils';
import { isNil, isString } from '../../../shared/utils';

const requests = new Map<string, Promise<unknown>>();

const fetchSvg = async (url: string, sanitize: boolean): Promise<unknown> => {
let req: Promise<unknown>;

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<string, string>();

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;
};

Expand Down

0 comments on commit 6da3a3f

Please sign in to comment.