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

能力: 無需

向頁面標頭貢獻 meta 標籤、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: ... }