Hook 参考

本页内容

Hook 允许插件在内容、媒体、电子邮件、评论和页面生命周期的特定点拦截和修改 EmDash 行为。

Hook 概述

下表列出了每个 Hook、触发它的条件、它可以修改的内容以及是否为独占性:

Hook触发器可修改独占性
content:beforeSave保存内容之前内容数据
content:afterSave保存内容之后
content:beforeDelete删除内容之前可取消
content:afterDelete删除内容之后
media:beforeUpload上传文件之前文件元数据
media:afterUpload上传文件之后
cron计划任务触发
email:beforeSend发送电子邮件之前消息,可取消
email:deliver通过传输方式发送电子邮件
email:afterSend电子邮件发送成功后
comment:beforeCreate存储评论之前评论,可取消
comment:moderate决定评论审核状态状态
comment:afterCreate存储评论之后
comment:afterModerate管理员更改评论状态之后
page:metadata渲染公共页面头部贡献标签
page:fragments渲染公共页面主体注入脚本
plugin:install首次安装插件时
plugin:activate启用插件时
plugin:deactivate禁用插件时
plugin:uninstall移除插件时

内容 Hook

content:beforeSave

在将内容保存到数据库之前运行。用于验证、转换或充实内容。

import { definePlugin } from "emdash";

export default definePlugin({
	id: "my-plugin",
	version: "1.0.0",
	hooks: {
		"content:beforeSave": async (event, ctx) => {
			const { content, collection, isNew } = event;

			// Add timestamps
			if (isNew) {
				content.createdBy = "system";
			}
			content.modifiedAt = new Date().toISOString();

			// Return modified content
			return content;
		},
	},
});

Event

interface ContentHookEvent {
	content: Record<string, unknown>; // Content data
	collection: string; // Collection slug
	isNew: boolean; // True for creates, false for updates
}

返回值

  • 返回修改后的内容对象以应用更改
  • 返回 void 以不做更改地通过

content:afterSave

在保存内容后运行。用于副作用,如通知、缓存失效或外部同步。

hooks: {
  "content:afterSave": async (event, ctx) => {
    const { content, collection, isNew } = event;

    if (collection === "posts" && content.status === "published") {
      // Notify external service
      await ctx.http?.fetch("https://api.example.com/notify", {
        method: "POST",
        body: JSON.stringify({ postId: content.id }),
      });
    }
  },
}

返回值

不需要返回值。

content:beforeDelete

在删除内容之前运行。用于验证删除或阻止删除。

hooks: {
  "content:beforeDelete": async (event, ctx) => {
    const { id, collection } = event;

    // Prevent deletion of protected content
    const item = await ctx.content?.get(collection, id);
    if (item?.data.protected) {
      return false; // Cancel deletion
    }

    // Allow deletion
    return true;
  },
}

Event

interface ContentDeleteEvent {
	id: string; // Entry ID
	collection: string; // Collection slug
}

返回值

  • 返回 false 以取消删除
  • 返回 truevoid 以允许

content:afterDelete

在删除内容后运行。用于清理任务。

hooks: {
  "content:afterDelete": async (event, ctx) => {
    const { id, collection } = event;

    // Clean up related data
    await ctx.storage.relatedItems.delete(`${collection}:${id}`);
  },
}

媒体 Hook

media:beforeUpload

在上传文件之前运行。用于验证、重命名或拒绝文件。

hooks: {
  "media:beforeUpload": async (event, ctx) => {
    const { file } = event;

    // Reject files over 10MB
    if (file.size > 10 * 1024 * 1024) {
      throw new Error("File too large");
    }

    // Rename file
    return {
      name: `${Date.now()}-${file.name}`,
      type: file.type,
      size: file.size,
    };
  },
}

Event

interface MediaUploadEvent {
	file: {
		name: string; // Original filename
		type: string; // MIME type
		size: number; // Size in bytes
	};
}

返回值

  • 返回修改后的文件元数据以应用更改
  • 返回 void 以不做更改地通过
  • 抛出异常以拒绝上传

media:afterUpload

在上传文件后运行。用于处理、缩略图或元数据提取。

hooks: {
  "media:afterUpload": async (event, ctx) => {
    const { media } = event;

    if (media.mimeType.startsWith("image/")) {
      // Store image metadata
      await ctx.kv.set(`media:${media.id}:analyzed`, {
        processedAt: new Date().toISOString(),
      });
    }
  },
}

Event

interface MediaAfterUploadEvent {
	media: {
		id: string;
		filename: string;
		mimeType: string;
		size: number | null;
		url: string;
		createdAt: string;
	};
}

生命周期 Hook

plugin:install

在首次安装插件时运行。用于初始设置、创建存储集合或种子数据。

hooks: {
  "plugin:install": async (event, ctx) => {
    // Initialize default settings
    await ctx.kv.set("settings:enabled", true);
    await ctx.kv.set("settings:threshold", 100);

    ctx.log.info("Plugin installed successfully");
  },
}

plugin:activate

在启用插件时运行(安装后或重新启用后)。

hooks: {
  "plugin:activate": async (event, ctx) => {
    ctx.log.info("Plugin activated");
  },
}

plugin:deactivate

在禁用插件时运行。

hooks: {
  "plugin:deactivate": async (event, ctx) => {
    ctx.log.info("Plugin deactivated");
  },
}

plugin:uninstall

在移除插件时运行。用于清理。

hooks: {
  "plugin:uninstall": async (event, ctx) => {
    const { deleteData } = event;

    if (deleteData) {
      // Clean up all plugin data
      const items = await ctx.kv.list("settings:");
      for (const { key } of items) {
        await ctx.kv.delete(key);
      }
    }

    ctx.log.info("Plugin uninstalled");
  },
}

Event

interface UninstallEvent {
	deleteData: boolean; // User chose to delete data
}

Cron Hook

cron

在计划任务执行时触发。使用 ctx.cron.schedule() 计划任务。

hooks: {
  "cron": async (event, ctx) => {
    if (event.name === "daily-sync") {
      const data = await ctx.http?.fetch("https://api.example.com/data");
      ctx.log.info("Sync complete");
    }
  },
}

Event

interface CronEvent {
	name: string;
	data?: Record<string, unknown>;
	scheduledAt: string;
}

电子邮件 Hook

电子邮件 Hook 按顺序运行:email:beforeSend,然后 email:deliver,然后 email:afterSend

email:beforeSend

能力: hooks.email-events:register

在发送之前运行的中间件 Hook。转换消息或取消发送。

hooks: {
  "email:beforeSend": async (event, ctx) => {
    // Add footer to all emails
    return {
      ...event.message,
      text: event.message.text + "\n\n—Sent from My Site",
    };

    // Or return false to cancel delivery
  },
}

Event

interface EmailBeforeSendEvent {
	message: { to: string; subject: string; text: string; html?: string };
	source: string;
}

返回值

  • 返回修改后的消息以转换
  • 返回 false 以取消发送
  • 返回 void 以不做更改地通过

email:deliver

能力: hooks.email-transport:register | 独占性:

传输提供者。只有一个插件可以发送电子邮件。负责通过电子邮件服务实际发送消息。

hooks: {
  "email:deliver": {
    exclusive: true,
    handler: async (event, ctx) => {
      await sendViaSES(event.message);
    },
  },
}

email:afterSend

能力: hooks.email-events:register

成功发送后的”触发即忘”Hook。错误会被记录但不会传播。

hooks: {
  "email:afterSend": async (event, ctx) => {
    await ctx.kv.set(`email:log:${Date.now()}`, {
      to: event.message.to,
      subject: event.message.subject,
    });
  },
}

评论 Hook

评论 Hook 按顺序运行:comment:beforeCreate,然后 comment:moderate,然后 comment:afterCreate。当管理员更改评论状态时,comment:afterModerate Hook 单独触发。

comment:beforeCreate

能力: users:read

存储评论之前的中间件 Hook。充实、验证或拒绝评论。

hooks: {
  "comment:beforeCreate": async (event, ctx) => {
    // Reject comments with links
    if (event.comment.body.includes("http")) {
      return false;
    }
  },
}

Event

interface CommentBeforeCreateEvent {
	comment: {
		collection: string;
		contentId: string;
		parentId: string | null;
		authorName: string;
		authorEmail: string;
		authorUserId: string | null;
		body: string;
		ipHash: string | null;
		userAgent: string | null;
	};
	metadata: Record<string, unknown>;
}

返回值

  • 返回修改后的事件以转换
  • 返回 false 以拒绝
  • 返回 void 以通过

comment:moderate

能力: users:read | 独占性:

决定评论是已批准、待审核还是垃圾邮件。只有一个审核提供者处于活动状态。

hooks: {
  "comment:moderate": {
    exclusive: true,
    handler: async (event, ctx) => {
      const score = await checkSpam(event.comment);
      return {
        status: score > 0.8 ? "spam" : score > 0.5 ? "pending" : "approved",
        reason: `Spam score: ${score}`,
      };
    },
  },
}

Event

interface CommentModerateEvent {
	comment: { /* same as beforeCreate */ };
	metadata: Record<string, unknown>;
	collectionSettings: {
		commentsEnabled: boolean;
		commentsModeration: "all" | "first_time" | "none";
		commentsClosedAfterDays: number;
		commentsAutoApproveUsers: boolean;
	};
	priorApprovedCount: number;
}

返回值

{ status: "approved" | "pending" | "spam"; reason?: string }

comment:afterCreate

能力: users:read

存储评论后的”触发即忘”Hook。用于通知。

hooks: {
  "comment:afterCreate": async (event, ctx) => {
    if (event.comment.status === "approved") {
      await ctx.email?.send({
        to: event.contentAuthor?.email,
        subject: `New comment on "${event.content.title}"`,
        text: `${event.comment.authorName} commented: ${event.comment.body}`,
      });
    }
  },
}

comment:afterModerate

能力: users:read

当管理员手动更改评论状态时的”触发即忘”Hook。

Event

interface CommentAfterModerateEvent {
	comment: { id: string; /* ... */ };
	previousStatus: string;
	newStatus: string;
	moderator: { id: string; name: string | null };
}

页面 Hook

页面 Hook 在渲染公共页面时运行。它们允许插件注入元数据和脚本。

page:metadata

能力: 无需

向页面头部贡献元标签、Open Graph 属性、JSON-LD 结构化数据或链接标签。

hooks: {
  "page:metadata": async (event, ctx) => {
    return [
      { kind: "meta", name: "generator", content: "EmDash" },
      { kind: "property", property: "og:site_name", content: event.page.siteName },
      { kind: "jsonld", graph: { "@type": "WebSite", name: event.page.siteName } },
    ];
  },
}

贡献类型

type PageMetadataContribution =
	| { kind: "meta"; name: string; content: string; key?: string }
	| { kind: "property"; property: string; content: string; key?: string }
	| {
			kind: "link";
			rel: "canonical" | "alternate" | "author" | "license" | "nlweb" | "site.standard.document";
			href: string;
			hreflang?: string;
			key?: string;
	  }
	| {
			kind: "jsonld";
			id?: string;
			graph: Record<string, unknown> | Array<Record<string, unknown>>;
	  };

key 字段对贡献进行去重 — 只使用具有给定键的最后一个贡献。

page:fragments

能力: hooks.page-fragments:register

向页面注入脚本或 HTML。仅适用于原生插件。

hooks: {
  "page:fragments": async (event, ctx) => {
    return [
      {
        kind: "external-script",
        placement: "body:end",
        src: "https://analytics.example.com/script.js",
        async: true,
      },
      {
        kind: "inline-script",
        placement: "head",
        code: `window.siteId = "abc123";`,
      },
    ];
  },
}

贡献类型

type PageFragmentContribution =
	| {
			kind: "external-script";
			placement: "head" | "body:start" | "body:end";
			src: string;
			async?: boolean;
			defer?: boolean;
			attributes?: Record<string, string>;
			key?: string;
		}
	| {
			kind: "inline-script";
			placement: "head" | "body:start" | "body:end";
			code: string;
			attributes?: Record<string, string>;
			key?: string;
		}
	| {
			kind: "html";
			placement: "head" | "body:start" | "body:end";
			html: string;
			key?: string;
		};

Hook 配置

Hook 接受处理函数或配置对象:

hooks: {
  // Simple handler
  "content:afterSave": async (event, ctx) => { ... },

  // With configuration
  "content:beforeSave": {
    priority: 50,        // Lower runs first (default: 100)
    timeout: 10000,      // Max execution time in ms (default: 5000)
    dependencies: [],    // Run after these plugins
    errorPolicy: "abort", // "continue" or "abort" (default)
    handler: async (event, ctx) => { ... },
  },
}

配置选项

选项类型默认值描述
prioritynumber100执行顺序(较低值先运行)
timeoutnumber5000最大执行时间(毫秒)
dependenciesstring[][]必须先运行的插件 ID
errorPolicystring"abort""continue" 以忽略错误
exclusivebooleanfalse只有一个插件可以成为活动提供者(用于提供者模式 Hook,如 email:delivercomment:moderate

插件上下文

所有 Hook 都接收一个上下文对象,可以访问插件 API:

interface PluginContext {
	plugin: { id: string; version: string };
	storage: PluginStorage;
	kv: KVAccess;
	content?: ContentAccess;
	media?: MediaAccess;
	http?: HttpAccess;
	log: LogAccess;
	site: { name: string; url: string; locale: string };
	url(path: string): string;
	users?: UserAccess;
	cron?: CronAccess;
	email?: EmailAccess;
}

有关能力要求和方法详细信息,请参阅插件概述 — 插件上下文

错误处理

Hook 中的错误会被记录并根据 errorPolicy 处理:

  • "abort"(默认)— 停止执行,如果适用则回滚事务
  • "continue" — 记录错误并继续下一个 Hook
hooks: {
  "content:beforeSave": {
    errorPolicy: "continue", // Don't block save if this fails
    handler: async (event, ctx) => {
      try {
        await ctx.http?.fetch("https://api.example.com/validate");
      } catch (error) {
        ctx.log.warn("Validation service unavailable", error);
      }
    },
  },
}

执行顺序

Hook 按以下顺序运行:

  1. priority 排序(升序)
  2. 具有 dependencies 的插件在其依赖项之后运行
  3. 在相同优先级内,顺序是确定性的但未指定
// This runs first (priority 10)
{ priority: 10, handler: ... }

// This runs second (priority 50)
{ priority: 50, handler: ... }

// This runs last (default priority 100)
{ handler: ... }