Files
shop/server/utils/cmsApi.ts
T
libretech fccff147ba
build / test (push) Successful in 10s
build / build (push) Successful in 1m5s
v0.1.2: checkout fixes for CMS v0.2.0 (#18)
Co-authored-by: Michael Czechowski <mail@librete.ch>
2026-10-15 10:23:27 +02:00

35 lines
1.2 KiB
TypeScript

import { cmsErrorLogLine, shopErrorFromCms } from "./cmsError";
/**
* Server-side CMS API utility.
* Use this for direct CMS access during SSR.
*/
export async function fetchCms<T>(endpoint: string, options: Parameters<typeof $fetch>[1] = {}): Promise<T> {
const config = useRuntimeConfig();
const url = `${config.cmsInternalUrl}/api${endpoint}`;
return await $fetch<T>(url, {
...options,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${config.shopApiToken}`,
...((options.headers as Record<string, string>) || {})
}
});
}
/**
* fetchCms for a route that forwards the browser's request to the CMS: a CMS error answers the browser with the CMS's status
* and the safe fields of its error (cmsError.ts), instead of an unhandled error, whose message and data Nitro hides.
*/
export async function forwardToCms<T>(endpoint: string, options: Parameters<typeof $fetch>[1] = {}): Promise<T> {
try {
return await fetchCms<T>(endpoint, options);
} catch (error) {
const shopError = shopErrorFromCms(error);
if (!shopError) throw error;
if (shopError.statusCode >= 500) console.error(cmsErrorLogLine(String(options.method ?? "GET"), endpoint, shopError));
throw createError(shopError);
}
}