插件 Storage

本页内容

插件可以将自有数据存入文档集合,而无需编写数据库 migration。在插件定义中声明集合与索引,EmDash 会自动处理 schema。

声明 Storage

definePlugin() 中定义 storage 集合:

import { definePlugin } from "emdash";

export default definePlugin({
	id: "forms",
	version: "1.0.0",

	storage: {
		submissions: {
			indexes: [
				"formId", // Single-field index
				"status",
				"createdAt",
				["formId", "createdAt"], // Composite index
				["status", "createdAt"],
			],
		},
		forms: {
			indexes: ["slug"],
		},
	},

	// ...
});

storage 中的每个键都是集合名。indexes 数组列出可高效查询的字段。

Storage 集合 API

在 hooks 与路由中通过 ctx.storage 访问集合:

"content:afterSave": async (event, ctx) => {
  const { submissions } = ctx.storage;

  // CRUD operations
  await submissions.put("sub_123", { formId: "contact", email: "[email protected]" });
  const item = await submissions.get("sub_123");
  const exists = await submissions.exists("sub_123");
  await submissions.delete("sub_123");
}

完整 API 参考

interface StorageCollection<T = unknown> {
	// Basic CRUD
	get(id: string): Promise<T | null>;
	put(id: string, data: T): Promise<void>;
	delete(id: string): Promise<boolean>;
	exists(id: string): Promise<boolean>;

	// Batch operations
	getMany(ids: string[]): Promise<Map<string, T>>;
	putMany(items: Array<{ id: string; data: T }>): Promise<void>;
	deleteMany(ids: string[]): Promise<number>;

	// Query (indexed fields only)
	query(options?: QueryOptions): Promise<PaginatedResult<{ id: string; data: T }>>;
	count(where?: WhereClause): Promise<number>;
}

查询数据

使用 query() 获取符合条件的文档。查询返回分页结果。

const result = await ctx.storage.submissions.query({
	where: {
		formId: "contact",
		status: "pending",
	},
	orderBy: { createdAt: "desc" },
	limit: 20,
});

// result.items - Array of { id, data }
// result.cursor - Pagination cursor (if more results)
// result.hasMore - Boolean indicating more pages

查询选项

interface QueryOptions {
	where?: WhereClause;
	orderBy?: Record<string, "asc" | "desc">;
	limit?: number; // Default 50, max 1000
	cursor?: string; // For pagination
}

Where 子句运算符

使用下列运算符按已索引字段筛选:

精确匹配

where: {
  status: "pending",        // Exact string match
  count: 5,                 // Exact number match
  archived: false           // Exact boolean match
}

范围

where: {
  createdAt: { gte: "2024-01-01" },     // Greater than or equal
  score: { gt: 50, lte: 100 }           // Between (exclusive/inclusive)
}

// Available: gt, gte, lt, lte

In(列表)

where: {
  status: { in: ["pending", "approved"] }
}

前缀匹配

where: {
  slug: { startsWith: "blog-" }
}

排序

按已索引字段排序:

orderBy: {
	createdAt: "desc";
} // Newest first
orderBy: {
	score: "asc";
} // Lowest first

分页

结果为分页返回。使用 cursor 获取后续页:

async function getAllSubmissions(ctx: PluginContext) {
	const allItems = [];
	let cursor: string | undefined;

	do {
		const result = await ctx.storage.submissions!.query({
			orderBy: { createdAt: "desc" },
			limit: 100,
			cursor,
		});

		allItems.push(...result.items);
		cursor = result.cursor;
	} while (cursor);

	return allItems;
}

PaginatedResult

interface PaginatedResult<T> {
	items: T[];
	cursor?: string; // Pass to next query for more results
	hasMore: boolean; // True if more pages exist
}

统计文档

统计符合条件的文档数量:

// Count all
const total = await ctx.storage.submissions!.count();

// Count with filter
const pending = await ctx.storage.submissions!.count({
	status: "pending",
});

批量操作

批量场景请使用批量方法:

// Get multiple by ID
const items = await ctx.storage.submissions!.getMany(["sub_1", "sub_2", "sub_3"]);
// Returns Map<string, T>

// Put multiple
await ctx.storage.submissions!.putMany([
	{ id: "sub_1", data: { formId: "contact", status: "new" } },
	{ id: "sub_2", data: { formId: "contact", status: "new" } },
]);

// Delete multiple
const deletedCount = await ctx.storage.submissions!.deleteMany(["sub_1", "sub_2"]);

索引设计

根据查询模式选择索引:

查询模式所需索引
formId 筛选"formId"
formId 筛选并按 createdAt 排序["formId", "createdAt"]
仅按 createdAt 排序"createdAt"
同时按 statusformId 筛选"status""formId"(分开)

复合索引支持先按第一个字段筛选、再可选按第二个字段排序的查询:

// With index ["formId", "createdAt"]:

// This works:
query({ where: { formId: "contact" }, orderBy: { createdAt: "desc" } });

// This also works (filter only):
query({ where: { formId: "contact" } });

// This does NOT use the composite index (wrong field order):
query({ where: { createdAt: { gte: "2024-01-01" } } });

类型安全

为 storage 集合添加类型以获得更好的 IntelliSense:

interface Submission {
	formId: string;
	email: string;
	data: Record<string, unknown>;
	status: "pending" | "approved" | "spam";
	createdAt: string;
}

definePlugin({
	id: "forms",
	version: "1.0.0",

	storage: {
		submissions: {
			indexes: ["formId", "status", "createdAt"],
		},
	},

	hooks: {
		"content:afterSave": async (event, ctx) => {
			// Cast to typed collection
			const submissions = ctx.storage.submissions as StorageCollection<Submission>;

			const submission: Submission = {
				formId: "contact",
				email: "[email protected]",
				data: { message: "Hello" },
				status: "pending",
				createdAt: new Date().toISOString(),
			};

			await submissions.put(`sub_${Date.now()}`, submission);
		},
	},
});

Storage 与内容与 KV

按场景选择合适的存储机制:

用例Storage
插件运行数据(日志、提交、缓存)ctx.storage
用户可配置设置settings: 前缀的 ctx.kv
插件内部状态state: 前缀的 ctx.kv
需在管理后台编辑的内容站点集合(非 plugin storage)

实现细节

底层实现中,plugin storage 使用单张数据库表:

CREATE TABLE _plugin_storage (
  plugin_id TEXT NOT NULL,
  collection TEXT NOT NULL,
  id TEXT NOT NULL,
  data JSON NOT NULL,
  created_at TEXT,
  updated_at TEXT,
  PRIMARY KEY (plugin_id, collection, id)
);

EmDash 会为已声明字段创建表达式索引:

CREATE INDEX idx_forms_submissions_formId
  ON _plugin_storage(json_extract(data, '$.formId'))
  WHERE plugin_id = 'forms' AND collection = 'submissions';

该设计提供:

  • 无需 migration — Schema 位于插件代码中
  • 可移植性 — 适用于 D1、libSQL、SQLite
  • 隔离性 — 插件只能访问自身数据
  • 安全性 — 无 SQL 注入,查询经过校验

添加索引

在插件更新中添加索引时,EmDash 会在下次启动时自动创建。这样做是安全的——可在不做数据迁移的情况下添加索引。

移除索引时,EmDash 会删除它们。对未索引字段的查询将因校验错误而失败。