UNPKG

@croct/plug

Version:

A fully-featured devkit for building natively personalized applications.

42 lines (41 loc) 1.27 kB
import { ContentFetcher } from "@croct/sdk/contentFetcher"; import { formatCause } from "@croct/sdk/error"; import { loadSlotContent } from "@croct/content"; function fetchContent(slotId, options) { const { apiKey, appId, fallback, baseEndpointUrl, logger, preferredLocale = "", ...fetchOptions } = options ?? {}; const auth = { appId, apiKey }; const [id, version = "latest"] = slotId.split("@"); const normalizedLocale = preferredLocale === "" ? void 0 : preferredLocale; const resolvedOptions = { ...fetchOptions, ...normalizedLocale !== void 0 ? { preferredLocale: normalizedLocale } : {}, ...version !== "latest" ? { version } : {} }; const promise = new ContentFetcher({ ...auth, baseEndpointUrl }).fetch(id, resolvedOptions); return promise.catch( async (error) => { if (logger !== void 0) { logger.error(`Failed to fetch content for slot "${id}@${version}": ${formatCause(error)}`); } if (fallback !== void 0) { return { content: fallback }; } const staticContent = await loadSlotContent(id, normalizedLocale); if (staticContent === null) { throw error; } return { content: staticContent }; } ); } export { fetchContent };