UNPKG

@query-api/react

Version:
123 lines (122 loc) 3.08 kB
import { jsx as M } from "react/jsx-runtime"; import { createContext as x, useContext as U, useMemo as f, useState as c, useEffect as P } from "react"; import { getValidSiteDetectionMode as h, getCurrentSite as S, getSiteUri as k, normalizeBearerToken as T, SITE_DETECTION_MODES as b, buildCraftQueryUrl as D } from "@query-api/js"; const v = x(void 0); function z({ config: t, location: e, children: r }) { const n = { config: t, location: e }; return /* @__PURE__ */ M(v.Provider, { value: n, children: r }); } function g() { const t = U(v); if (t === void 0) throw new Error("useCraftContext must be used within the CraftProvider"); return t; } function a() { const { config: t } = g(); if (t === void 0) throw new Error("you must provide a valid config in the CraftProvider"); return t; } function A() { const { location: t } = g(); if (t === void 0) throw new Error("you must provide a valid location in the CraftProvider"); return t; } function L() { const { contentMapping: t } = a(); if (t === void 0) throw new Error( "You can not use getContentMapping if you don not provide a valid contentMapping in the CraftProvider." ); return t; } function B() { const { siteMap: t, siteDetectionMode: e } = a(); if (!t || t.length === 0) throw new Error( "Invalid sitemap configuration. Please provide a valid sitemap in your craftInit()." ); const r = h(e), n = p(r); return f(() => S(t, n, r), [t, n, r]); } function N() { const { siteDetectionMode: t } = a(), e = B(), r = h(t), n = p(r); return f(() => k(n, e, r), [n, e, r]); } function I() { const { authToken: t } = a(); if (!t) throw new Error( "CraftCMS Auth Token is missing. Please provide a valid token in your craftInit()." ); return T(t); } function p(t) { const e = A(); return f(() => t === b.PATH ? e.pathname : e.absoluteUrl, [t, e]); } function C(t, e = {}) { const [r, n] = c(null), [w, l] = c(!0), [m, d] = c(null), u = I(), { baseUrl: y, debug: E } = a(), i = `${y}${t}`; return E && console.log(i), P(() => { if (!i || !u) throw new Error("Please provide a valid url and auth token"); l(!0), d(null), fetch(i, { ...e, headers: { ...e.headers || {}, Authorization: u } }).then(async (o) => { if (!o.ok) throw new Error(await o.text()); return o.json(); }).then(n).catch((o) => d(o.message)).finally(() => l(!1)); }, [i, u, JSON.stringify(e)]), { data: r, loading: w, error: m }; } function s(t) { const e = D(t); return { ...e, one() { const r = e.buildBaseUrl("one"); return C(r); }, all() { const r = e.buildBaseUrl("all"); return C(r); } }; } function Q() { return s("entries"); } function _() { return s("users"); } function $() { return s("assets"); } function H() { return s("addresses"); } export { v as C, z as a, a as b, A as c, L as d, B as e, N as f, I as g, C as h, s as i, Q as j, _ as k, $ as l, H as m, g as u };