import { MARKA_API_KEY } from "../env.ts"; import { getImage } from "../image.ts"; import { GenericResource } from "./schema.ts"; const url = `https://marka.max-richter.dev`; //const url = "http://localhost:8080"; async function addImageToResource( resource: GenericResource, ): Promise { const imageUrl = resource?.content?.image; if (imageUrl) { try { const absoluteImageUrl = (imageUrl.startsWith("https://") || imageUrl.startsWith("http://")) ? imageUrl : `${url}/${imageUrl}`; const image = await getImage(absoluteImageUrl); return { ...resource, image } as T; } catch (e) { console.log(`Failed to fetch image: ${imageUrl}`, e); } } return resource as T; } export async function fetchResource( resource: string, ): Promise { try { const response = await fetch( `${url}/resources/${resource}`, ); const res = await response.json(); return addImageToResource(res); } catch (_e) { return; } } export async function listResources( resource: string, ): Promise { try { const response = await fetch( `${url}/resources/${resource}`, ); const list = await response.json(); return Promise.all( list?.content .filter((a: GenericResource) => a?.content?._type) .map((res: GenericResource) => addImageToResource(res)), ); } catch (_e) { return []; } } export async function createResource( path: string, content: string | object | ArrayBuffer, ) { const isJson = typeof content === "object" && !(content instanceof ArrayBuffer); const fetchUrl = `${url}/resources/${path}`; const headers = new Headers(); headers.append("Content-Type", isJson ? "application/json" : ""); if (MARKA_API_KEY) { headers.append("Authentication", MARKA_API_KEY); } const response = await fetch(fetchUrl, { method: "POST", headers, body: isJson ? JSON.stringify(content) : content, }); if (!response.ok) { throw new Error(`Failed to create resource: ${response.status}`); } return response.json(); }