UNPKG

@sensinum/astro-strapi-loader

Version:
87 lines (86 loc) 3.25 kB
import { defineCollection } from "astro:content"; import { StrapiSchemaGenerator } from "./schema"; import { strapiLoader } from "./loader"; async function strapiRequest(options) { const { url, token, path, headers: extraHeaders = {} } = options; const headers = { "Content-Type": "application/json", ...extraHeaders, }; if (token) { headers["Authorization"] = `Bearer ${token}`; } const response = await fetch(`${url}/api/${path}`, { headers, method: "GET", }); if (!response.ok) { throw new Error(`Failed to fetch from Strapi: ${response.statusText}`); } return response.json(); } export async function fetchContentTypes(options) { const contentTypes = await strapiRequest({ ...options, path: "content-type-builder/content-types", }); return contentTypes.data.filter((contentType) => !contentType.plugin); } export async function fetchComponents(options) { const components = await strapiRequest({ ...options, path: "content-type-builder/components", }); return components.data; } export async function fetchContent(options) { const { url, token, contentType, queryParams, headers } = options; const path = `${contentType}${queryParams ? `/?${queryParams}` : ""}`; return strapiRequest({ url, token, path, headers, }); } export async function generateStrapiSchema(options) { const { url, token, strict } = options; const contentTypes = await fetchContentTypes({ url, token }); const components = await fetchComponents({ url, token }); const schemaGenerator = new StrapiSchemaGenerator(contentTypes, components, strict); return schemaGenerator.generateAllSchemas(); } export function generateCollection(contentType, schema, options, collectionConfig = {}) { const { query = {}, collectionName, idGenerator, locale } = collectionConfig; const loaderOptions = { ...options, collectionName, idGenerator, locale, }; return defineCollection({ loader: strapiLoader(contentType, loaderOptions, query), schema, }); } export async function generateCollections(options, reqCollections = []) { const schema = await generateStrapiSchema(options); const allCollections = Object.keys(schema); const demandedCollections = reqCollections.length > 0 ? allCollections.filter((collection) => reqCollections .map((reqCollection) => typeof reqCollection === "string" ? reqCollection : reqCollection.name) .includes(collection)) : allCollections; const collections = demandedCollections.reduce((acc, collection) => { const reqCollection = reqCollections.find((rc) => typeof rc === "string" ? rc === collection : rc.name === collection); const collectionConfig = typeof reqCollection === "string" ? {} : reqCollection || {}; const collectionKey = collectionConfig.collectionName || collection; return { ...acc, [collectionKey]: generateCollection(collection, schema[collection], options, collectionConfig), }; }, {}); return collections; }