我们很高兴地宣布,Hygraph 成为 Astro Content Layer 的首发合作伙伴,这是我们将外部 CMS 内容引入内容集合的新方法。Hygraph 是一个 API 优先的 CMS,它能让你组织复杂的结构化内容,并使用任何前端技术构建高性能、内容驱动的应用程序。
内容集合允许你将各种类型的内容整合到一个 API 中。通过内容层 (Content Layer),现在可以从各种外部源(例如 Hygraph CMS)引入内容。
使用 Hygraph 加载器
要使用新的加载器(测试版),请先安装 @hygraph/hygraph-astro-loader
包
npm install @hygraph/hygraph-astro-loader
在 Hygraph 仪表盘中,找到你的 API 端点并复制 URL,然后将其作为环境变量提供,命名为 HYGRAPH_ENDPOINT
之类的名称。
然后在你的 src/content/config.ts
配置文件中导入并使用该加载器
import { defineCollection, z } from 'astro:content';import { HygraphLoader } from '@hygraph/hygraph-astro-loader';
const pages = defineCollection({ loader: HygraphLoader({ endpoint: import.meta.env.HYGRAPH_ENDPOINT, operation: 'pages', fields: ["id", "title", "slug", { "body": ["text"] }], }),
schema: z.object({ id: z.string(), title: z.string({ required_error: 'Title is required' }).min(1, { message: 'Title is required to be at least 1 character' }), slug: z.string(), body: z.object({ text: z.string(), }), })})
export const collections = { pages }
就是这样,从这里开始,你就可以像查询和使用本地集合一样查询和使用这些集合了。要了解更多信息,请参阅 Astro 关于内容集合的文档。
另外,请查看昨天关于内容层 (Content Layer) 的深度解析,以了解加载器的工作原理以及如何构建自己的加载器。也欢迎查看 Hygraph 加载器的 GitHub 仓库来报告问题和做出贡献。