JavaScript API 参考

本页内容

EmDash 导出用于查询内容以及处理预览、设置、菜单、分类、小部件区域、分区和搜索的函数。

内容查询

EmDash 的查询函数遵循 Astro 的 实时内容集合 模式,返回 { entries, error }{ entry, error } 以优雅地处理错误。

getEmDashCollection()

从集合中获取所有条目。以下示例加载所有文章并检查错误:

import { getEmDashCollection } from "emdash";

const { entries: posts, error } = await getEmDashCollection("posts");

if (error) {
	console.error("Failed to load posts:", error);
}

参数

参数类型描述
collectionstring集合 slug
optionsCollectionFilter可选的过滤器选项

选项

options 参数接受以下过滤器:

interface CollectionFilter {
	status?: "draft" | "published" | "archived";
	limit?: number;
	where?: Record<string, string | string[]>; // Filter by field or taxonomy
}

返回值

该函数解析为 CollectionResult

interface CollectionResult<T> {
	entries: ContentEntry<T>[]; // Empty array if error or none found
	error?: Error; // Set if query failed
}

示例

以下示例按状态和分类过滤、限制结果并处理错误:

// Get all published posts
const { entries: posts } = await getEmDashCollection("posts", {
	status: "published",
});

// Get latest 5 posts
const { entries: latest } = await getEmDashCollection("posts", {
	limit: 5,
	status: "published",
});

// Filter by taxonomy
const { entries: newsPosts } = await getEmDashCollection("posts", {
	status: "published",
	where: { category: "news" },
});

// Handle errors
const { entries, error } = await getEmDashCollection("posts");
if (error) {
	return new Response("Server error", { status: 500 });
}

getEmDashEntry()

通过 slug 或 ID 获取单个条目。以下示例加载一篇文章,并在缺失时重定向:

import { getEmDashEntry } from "emdash";

const { entry: post, error } = await getEmDashEntry("posts", "my-post-slug");

if (!post) {
	return Astro.redirect("/404");
}

参数

参数类型描述
collectionstring集合 slug
slugOrIdstring条目 slug 或 ID
options{ locale?: string }可选。用于 slug 解析的语言环境

预览模式会自动处理——中间件检测 _preview 令牌并通过 AsyncLocalStorage 提供草稿内容。可选的 options 参数仅接受用于 slug 解析的 locale;预览状态不需要参数。

返回值

该函数解析为 EntryResult

interface EntryResult<T> {
	entry: ContentEntry<T> | null; // null if not found
	error?: Error; // Set only for actual errors, not "not found"
	isPreview: boolean; // true if draft content is being served
}

示例

以下示例通过 slug 和 ID 获取、读取预览状态并区分错误和”未找到”:

// Get by slug
const { entry: post } = await getEmDashEntry("posts", "hello-world");

// Get by ID
const { entry: post } = await getEmDashEntry("posts", "01HXK5MZSN0FVXT2Q3KPRT9M7D");

// Preview is automatic — isPreview is true when a valid _preview token is present
const { entry, isPreview, error } = await getEmDashEntry("posts", slug);

// Handle errors vs not-found
if (error) {
	return new Response("Server error", { status: 500 });
}
if (!entry) {
	return Astro.redirect("/404");
}

内容类型

ContentEntry

查询函数以以下形式返回条目:

interface ContentEntry<T = Record<string, unknown>> {
	id: string;
	data: T;
	edit: EditProxy; // Visual editing annotations
}

edit 代理提供可视化编辑注释。将其展开到元素上以启用内联编辑:{...entry.edit.title}。在生产环境中,这不会产生输出。

data 对象包含所有内容字段以及系统字段:

  • id - 唯一标识符
  • slug - URL 友好标识符
  • status - “draft” | “published” | “archived”
  • createdAt - ISO 时间戳
  • updatedAt - ISO 时间戳
  • publishedAt - ISO 时间戳或 null
  • 加上集合模式中定义的所有自定义字段

预览系统

generatePreviewToken()

为草稿内容生成预览令牌。以下示例创建一个在一小时后过期的令牌:

import { generatePreviewToken } from "emdash";

const token = await generatePreviewToken({
	contentId: "posts:01HXK5MZSN...",
	secret: process.env.EMDASH_ADMIN_SECRET,
	expiresIn: 3600, // 1 hour
});

verifyPreviewToken()

验证预览令牌并读取其有效载荷:

import { verifyPreviewToken } from "emdash";

const result = await verifyPreviewToken({
	token,
	secret: process.env.EMDASH_ADMIN_SECRET,
});

if (result.valid) {
	const { cid, exp, iat } = result.payload;
	// cid is "collection:id" format, e.g. "posts:my-draft-post"
}

isPreviewRequest()

检查请求是否包含预览令牌,然后读取它:

import { isPreviewRequest, getPreviewToken } from "emdash";

if (isPreviewRequest(Astro.url)) {
	const token = getPreviewToken(Astro.url);
	// Verify and show preview content
}

内容转换器

在 Portable Text 和 ProseMirror 格式之间转换:

import { prosemirrorToPortableText, portableTextToProsemirror } from "emdash";

// From ProseMirror (editor) to Portable Text (storage)
const portableText = prosemirrorToPortableText(prosemirrorDoc);

// From Portable Text to ProseMirror
const prosemirrorDoc = portableTextToProsemirror(portableText);

站点设置

使用 getSiteSettingsgetSiteSetting 读取全站设置:

import { getSiteSettings, getSiteSetting } from "emdash";

// Get all settings
const settings = await getSiteSettings();

// Get single setting
const title = await getSiteSetting("title");

设置从运行时 API 只读。使用管理员 API 更新它们。

菜单

获取导航菜单并遍历它们的项目,包括嵌套的子项:

import { getMenu, getMenus } from "emdash";

// Get all menus
const menus = await getMenus();

// Get specific menu with items
const primaryMenu = await getMenu("primary");

if (primaryMenu) {
	primaryMenu.items.forEach(item => {
		console.log(item.label, item.url);
		// Nested items for dropdowns
		item.children.forEach(child => console.log("  -", child.label));
	});
}

分类

获取分类术语、单个术语、条目的术语或按术语获取条目:

import { getTaxonomyTerms, getTerm, getEntryTerms, getEntriesByTerm } from "emdash";

// Get all terms for a taxonomy (tree structure for hierarchical)
const categories = await getTaxonomyTerms("category");

// Get single term
const news = await getTerm("category", "news");

// Get terms assigned to a content entry
const postCategories = await getEntryTerms("posts", "post-123", "category");

// Get entries with a specific term
const newsPosts = await getEntriesByTerm("posts", "category", "news");

小部件区域

获取小部件区域及其包含的小部件:

import { getWidgetArea, getWidgetAreas } from "emdash";

// Get all widget areas
const areas = await getWidgetAreas();

// Get specific widget area with widgets
const sidebar = await getWidgetArea("sidebar");

if (sidebar) {
	sidebar.widgets.forEach(widget => {
		console.log(widget.type, widget.title);
	});
}

分区

获取分区并对其进行过滤:

import { getSection, getSections } from "emdash";

// Get all sections (paginated)
const { items, nextCursor } = await getSections();

// Filter sections
const { items: themeSections } = await getSections({ source: "theme" });
const { items: results } = await getSections({ search: "newsletter" });

// Get a single section by slug
const cta = await getSection("newsletter-cta");

getSections(options?) 返回 { items: Section[]; nextCursor?: string }。选项包括 source ("theme" | "user" | "import")、searchlimit(默认 50,最大 100)和 cursor

搜索

跨集合运行全局搜索。结果包括高亮摘录:

import { search } from "emdash";

const results = await search("hello world", {
	collections: ["posts", "pages"],
	status: "published",
	limit: 20,
});

// search() resolves to { items, nextCursor? }
results.items.forEach(result => {
	console.log(result.title);
	console.log(result.snippet); // Contains <mark> tags
	console.log(result.score);
});

错误处理

EmDash 导出用于处理特定失败的错误类。以下示例捕获验证和模式错误:

import {
  EmDashDatabaseError,
  EmDashValidationError,
  EmDashStorageError,
  SchemaError,
} from "emdash";

try {
  await repo.create({ ... });
} catch (error) {
  if (error instanceof EmDashValidationError) {
    console.error("Validation failed:", error.message);
  }
  if (error instanceof SchemaError) {
    console.error("Schema error:", error.code, error.details);
  }
}