@sensinum/astro-strapi-loader
Version:
Astro loader for Strapi CMS
69 lines (68 loc) • 2.57 kB
JavaScript
import { defineCollection } from "astro:content";
import { StrapiSchemaGenerator } from "./schema";
import { strapiLoader } from "./loader";
async function strapiRequest(options) {
const { url, token, path } = options;
const headers = {
"Content-Type": "application/json",
};
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 fetchContent(options) {
const { url, token, contentType, queryParams } = options;
const path = `${contentType}${queryParams ? `/?${queryParams}` : ""}`;
return strapiRequest({
url,
token,
path,
});
}
export async function generateStrapiSchema(options) {
const { url, token, strict } = options;
const contentTypes = await fetchContentTypes({ url, token });
const schemaGenerator = new StrapiSchemaGenerator(contentTypes, strict);
return schemaGenerator.generateAllSchemas();
}
export function generateCollection(contentType, schema, options, query = {}) {
return defineCollection({
loader: strapiLoader(contentType, options, 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 : rc.name === collection);
const query = typeof reqCollection === "string" ? {} : reqCollection?.query || {};
return {
...acc,
[collection]: generateCollection(collection, schema[collection], options, query),
};
}, {});
return collections;
}