コンテンツにスキップ

JavaScript API リファレンス

EmDashは、コンテンツのクエリ、メディアの管理、データベースの操作を行うための関数をエクスポートします。

EmDashのクエリ関数はAstroのライブコンテンツコレクションパターンに従い、エラーを適切に処理するために{ entries, error }または{ entry, error }を返します。

コレクションからすべてのエントリを取得します。

import { getEmDashCollection } from "emdash";
const { entries: posts, error } = await getEmDashCollection("posts");
if (error) {
console.error("Failed to load posts:", error);
}
パラメータ型説明
collectionstringコレクションスラッグ
optionsCollectionFilterオプションのフィルターオプション
interface CollectionFilter {
status?: "draft" | "published" | "archived";
limit?: number;
where?: Record<string, string | string[]>; // Filter by field or taxonomy
}
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",
});
// 最新の5件の投稿を取得
const { entries: latest } = await getEmDashCollection("posts", {
limit: 5,
status: "published",
});
// タクソノミーでフィルター
const { entries: newsPosts } = await getEmDashCollection("posts", {
status: "published",
where: { category: "news" },
});
// エラー処理
const { entries, error } = await getEmDashCollection("posts");
if (error) {
return new Response("Server error", { status: 500 });
}

スラッグまたはIDで単一のエントリを取得します。

import { getEmDashEntry } from "emdash";
const { entry: post, error } = await getEmDashEntry("posts", "my-post-slug");
if (!post) {
return Astro.redirect("/404");
}
パラメータ型説明
collectionstringコレクションスラッグ
slugOrIdstringエントリスラッグまたはID

プレビューモードは自動的に処理されます — ミドルウェアが_previewトークンを検出し、AsyncLocalStorageを介して下書きコンテンツを提供します。オプションパラメータは必要ありません。

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
}
// Get by slug
const { entry: post } = await getEmDashEntry("posts", "hello-world");
// IDで取得
const { entry: post } = await getEmDashEntry("posts", "01HXK5MZSN0FVXT2Q3KPRT9M7D");
// プレビューは自動的 — 有効な_previewトークンが存在する場合、isPreviewはtrueになります
const { entry, isPreview, error } = await getEmDashEntry("posts", slug);
// エラーと見つからない場合の処理
if (error) {
return new Response("Server error", { status: 500 });
}
if (!entry) {
return Astro.redirect("/404");
}

クエリ関数によって返されるエントリ:

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
  • コレクションスキーマで定義されたすべてのカスタムフィールド

データベース接続を作成します。

import { createDatabase } from "emdash";
const db = createDatabase({ url: "file:./data.db" });

保留中のデータベースマイグレーションを実行します。

import { createDatabase, runMigrations } from "emdash";
const db = createDatabase({ url: "file:./data.db" });
const { applied } = await runMigrations(db);
console.log(`Applied ${applied.length} migrations`);

マイグレーションの状態を確認します。

import { createDatabase, getMigrationStatus } from "emdash";
const db = createDatabase({ url: "file:./data.db" });
const status = await getMigrationStatus(db);
// { applied: ["0001_core", ...], pending: [] }

リポジトリを通じた低レベルのデータアクセス。

import { ContentRepository, createDatabase } from "emdash";
const db = createDatabase({ url: "file:./data.db" });
const repo = new ContentRepository(db);
// 複数検索
const { items, nextCursor } = await repo.findMany("posts", {
limit: 10,
where: { status: "published" },
});
// IDで検索
const post = await repo.findById("posts", "01HXK5MZSN...");
// 作成
const newPost = await repo.create({
type: "posts",
slug: "new-post",
data: { title: "New Post", content: [] },
status: "draft",
});
// 更新
const updated = await repo.update("posts", "01HXK5MZSN...", {
data: { title: "Updated Title" },
});
// 削除
await repo.delete("posts", "01HXK5MZSN...");
import { MediaRepository, createDatabase } from "emdash";
const db = createDatabase({ url: "file:./data.db" });
const repo = new MediaRepository(db);
// メディア一覧
const { items } = await repo.findMany({ limit: 20 });
// IDで取得
const media = await repo.findById("01HXK5MZSN...");
// 作成(アップロード後)
const newMedia = await repo.create({
filename: "photo.jpg",
mimeType: "image/jpeg",
size: 12345,
storageKey: "uploads/photo.jpg",
});

プログラムによるスキーマ管理。

import { SchemaRegistry, createDatabase } from "emdash";
const db = createDatabase({ url: "file:./data.db" });
const registry = new SchemaRegistry(db);
// コレクション一覧
const collections = await registry.listCollections();
// フィールドを含むコレクションを取得
const postsSchema = await registry.getCollectionWithFields("posts");
// コレクション作成
await registry.createCollection({
slug: "products",
label: "Products",
labelSingular: "Product",
supports: ["drafts", "revisions"],
});
// フィールド追加
await registry.createField("products", {
slug: "price",
label: "Price",
type: "number",
required: true,
});

下書きコンテンツ用のプレビュートークンを生成します。

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

プレビュートークンを検証します。

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は「collection:id」形式、例: "posts:my-draft-post"
}

リクエストにプレビュートークンが含まれているか確認します。

import { isPreviewRequest, getPreviewToken } from "emdash";
if (isPreviewRequest(Astro.request)) {
const token = getPreviewToken(Astro.request);
// Verify and show preview content
}

Portable TextとProseMirror形式の間で変換します。

import { prosemirrorToPortableText, portableTextToProsemirror } from "emdash";
// ProseMirror(エディタ)からPortable Text(ストレージ)へ
const portableText = prosemirrorToPortableText(prosemirrorDoc);
// Portable TextからProseMirrorへ
const prosemirrorDoc = portableTextToProsemirror(portableText);
import { getSiteSettings, getSiteSetting } from "emdash";
// すべての設定を取得
const settings = await getSiteSettings();
// 単一の設定を取得
const title = await getSiteSetting("siteTitle");

設定はランタイムAPIからは読み取り専用です。更新するには管理APIを使用してください。

import { getMenu, getMenus } from "emdash";
// すべてのメニューを取得
const menus = await getMenus();
// 特定のメニューをアイテムとともに取得
const primaryMenu = await getMenu("primary");
if (primaryMenu) {
primaryMenu.items.forEach(item => {
console.log(item.label, item.url);
// ドロップダウン用のネストされた項目
item.children.forEach(child => console.log(" -", child.label));
});
}
import { getTaxonomyTerms, getTerm, getEntryTerms, getEntriesByTerm } from "emdash";
// タクソノミーのすべての用語を取得(階層構造の場合はツリー構造)
const categories = await getTaxonomyTerms("category");
// 単一のタームを取得
const news = await getTerm("category", "news");
// コンテンツエントリに割り当てられたタームを取得
const postCategories = await getEntryTerms("posts", "post-123", "category");
// 特定のタームを持つエントリを取得
const newsPosts = await getEntriesByTerm("posts", "category", "news");
import { getWidgetArea, getWidgetAreas } from "emdash";
// すべてのウィジェットエリアを取得
const areas = await getWidgetAreas();
// ウィジェットを含む特定のウィジェットエリアを取得
const sidebar = await getWidgetArea("sidebar");
if (sidebar) {
sidebar.widgets.forEach(widget => {
console.log(widget.type, widget.title);
});
}
import { getSection, getSections, getSectionCategories } from "emdash";
// すべてのセクションを取得
const sections = await getSections();
// セクションをフィルタリング
const heroes = await getSections({ category: "hero" });
const themeSections = await getSections({ source: "theme" });
const results = await getSections({ search: "newsletter" });
// 単一のセクションを取得
const cta = await getSection("newsletter-cta");
// カテゴリを取得
const categories = await getSectionCategories();
import { search, searchCollection } from "emdash";
// コレクション全体でのグローバル検索
const results = await search("hello world", {
collections: ["posts", "pages"],
status: "published",
limit: 20,
});
// 結果にはハイライト付きのスニペットが含まれる
results.forEach(result => {
console.log(result.title);
console.log(result.snippet); // Contains <mark> tags
console.log(result.score);
});
// コレクション固有の検索
const posts = await searchCollection("posts", "typescript", {
limit: 10,
});

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);
}
}