reworked astro collections
This commit is contained in:
68
client/src/lib/strapi.ts
Normal file
68
client/src/lib/strapi.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
interface Props {
|
||||
endpoint: string;
|
||||
query?: Record<string, string>;
|
||||
wrappedByKey?: string;
|
||||
wrappedByList?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches data from the Strapi API
|
||||
* @param endpoint - The endpoint to fetch from
|
||||
* @param query - The query parameters to add to the url
|
||||
* @param wrappedByKey - The key to unwrap the response from
|
||||
* @param wrappedByList - If the response is a list, unwrap it
|
||||
* @returns
|
||||
*/
|
||||
export default async function fetchApi<T>({
|
||||
endpoint,
|
||||
query,
|
||||
wrappedByKey,
|
||||
wrappedByList,
|
||||
}: Props): Promise<T> {
|
||||
if (endpoint.startsWith('/')) {
|
||||
endpoint = endpoint.slice(1);
|
||||
}
|
||||
const strapiUrl = import.meta.env.STRAPI_URL || process.env.STRAPI_URL || "http://localhost:1337";
|
||||
console.log(strapiUrl);
|
||||
const url = new URL(`${strapiUrl}/api/${endpoint}`);
|
||||
|
||||
if (query) {
|
||||
Object.entries(query).forEach(([key, value]) => {
|
||||
url.searchParams.append(key, value);
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString());
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP error! status: ${res.status}`);
|
||||
}
|
||||
|
||||
let data = await res.json();
|
||||
|
||||
if (wrappedByKey) {
|
||||
data = data[wrappedByKey];
|
||||
}
|
||||
|
||||
if (wrappedByList) {
|
||||
data = data[0];
|
||||
}
|
||||
|
||||
return data as T;
|
||||
} catch (error) {
|
||||
console.error('Error fetching from Strapi API:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to handle media URLs from Strapi
|
||||
export function getStrapiMedia(url: string | null, baseUrl: string) {
|
||||
if (url == null) return null;
|
||||
// Return as-is if it's a data URL (base64)
|
||||
if (url.startsWith("data:")) return url;
|
||||
// Return as-is if it's an absolute URL
|
||||
if (url.startsWith("http") || url.startsWith("//")) return url;
|
||||
// Prepend baseUrl for relative URLs
|
||||
return `${baseUrl}${url}`;
|
||||
}
|
||||
Reference in New Issue
Block a user