鉤子允許外掛在內容、媒體、郵件、留言和頁面生命週期的特定節點攔截和修改 EmDash 的行為。
鉤子概覽
下表列出每個鉤子、觸發條件、可修改內容以及是否為排他性鉤子:
| 鉤子 | 觸發條件 | 可修改 | 排他性 |
|---|---|---|---|
content:beforeSave | 內容儲存前 | 內容資料 | 否 |
content:afterSave | 內容儲存後 | 無 | 否 |
content:beforeDelete | 內容刪除前 | 可取消 | 否 |
content:afterDelete | 內容刪除後 | 無 | 否 |
content:afterPublish | 內容發布後 | 無 | 否 |
content:afterUnpublish | 內容取消發布後 | 無 | 否 |
content:afterRestore | 內容還原後 | 無 | 否 |
content:afterSchedule | 內容排程後 | 無 | 否 |
content:afterUnschedule | 內容取消排程後 | 無 | 否 |
media:beforeUpload | 檔案上傳前 | 檔案中繼資料 | 否 |
media:afterUpload | 檔案上傳後 | 無 | 否 |
cron | 排程任務執行 | 無 | 否 |
email:beforeSend | 郵件發送前 | 訊息,可取消 | 否 |
email:deliver | 透過傳輸層傳送郵件 | 無 | 是 |
email:afterSend | 郵件發送成功後 | 無 | 否 |
comment:beforeCreate | 留言儲存前 | 留言,可取消 | 否 |
comment:moderate | 決定留言審核狀態 | 狀態 | 是 |
comment:afterCreate | 留言儲存後 | 無 | 否 |
comment:afterModerate | 管理員更改留言狀態後 | 無 | 否 |
page:metadata | 渲染公開頁面 head | 貢獻標籤 | 否 |
page:fragments | 渲染公開頁面 body | 注入腳本 | 否 |
plugin:install | 外掛首次安裝時 | 無 | 否 |
plugin:activate | 外掛啟用時 | 無 | 否 |
plugin:deactivate | 外掛停用時 | 無 | 否 |
plugin:uninstall | 外掛移除時 | 無 | 否 |
內容鉤子
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;
if (isNew) {
content.createdBy = "system";
}
content.modifiedAt = new Date().toISOString();
return content;
},
},
});
Event
interface ContentHookEvent {
content: Record<string, unknown>;
collection: string;
isNew: boolean;
}
回傳值
- 回傳修改後的內容物件以套用變更
- 回傳
void以不做更改通過
content:afterSave
內容儲存後執行。用於通知、快取失效或外部同步等副作用。
hooks: {
"content:afterSave": async (event, ctx) => {
const { content, collection, isNew } = event;
if (collection === "posts" && content.status === "published") {
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;
const item = await ctx.content?.get(collection, id);
if (item?.data.protected) {
return false;
}
return true;
},
}
Event
interface ContentDeleteEvent {
id: string;
collection: string;
}
回傳值
- 回傳
false以取消刪除 - 回傳
true或void以允許
content:afterDelete
內容刪除後執行。用於清理任務。
hooks: {
"content:afterDelete": async (event, ctx) => {
const { id, collection } = event;
await ctx.storage.relatedItems.delete(`${collection}:${id}`);
},
}
content:afterRestore
已刪除內容還原後執行。需要 content:read 能力。
hooks: {
"content:afterRestore": async (event, ctx) => {
ctx.log.info(`Restored ${event.collection}/${event.content.id}`);
},
}
content:afterSchedule
內容排程發布設定後執行。需要 content:read 能力。
hooks: {
"content:afterSchedule": async (event, ctx) => {
ctx.log.info(`Scheduled ${event.collection}/${event.content.id}`);
},
}
content:afterUnschedule
排程內容取消排程後執行。需要 content:read 能力。
hooks: {
"content:afterUnschedule": async (event, ctx) => {
ctx.log.info(`Unscheduled ${event.collection}/${event.content.id}`);
},
}
Event
interface ContentStateChangeEvent {
content: Record<string, unknown>;
collection: string;
}
回傳值
不需要回傳值。
媒體鉤子
media:beforeUpload
檔案上傳前執行。用於驗證、重新命名或拒絕檔案。
hooks: {
"media:beforeUpload": async (event, ctx) => {
const { file } = event;
if (file.size > 10 * 1024 * 1024) {
throw new Error("File too large");
}
return {
name: `${Date.now()}-${file.name}`,
type: file.type,
size: file.size,
};
},
}
Event
interface MediaUploadEvent {
file: {
name: string;
type: string;
size: number;
};
}
回傳值
- 回傳修改後的檔案中繼資料以套用變更
- 回傳
void以不做更改通過 - 拋出錯誤以拒絕上傳
media:afterUpload
檔案上傳後執行。用於處理、縮圖或中繼資料擷取。
hooks: {
"media:afterUpload": async (event, ctx) => {
const { media } = event;
if (media.mimeType.startsWith("image/")) {
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;
};
}
生命週期鉤子
plugin:install
外掛首次安裝時執行。用於初始設定、建立儲存集合或資料播種。
hooks: {
"plugin:install": async (event, ctx) => {
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) {
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;
}
Cron 鉤子
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;
}
郵件鉤子
郵件鉤子按順序執行:email:beforeSend,然後 email:deliver,然後 email:afterSend。
email:beforeSend
能力: hooks.email-events:register
在投遞前執行的中介軟體鉤子。轉換訊息或取消投遞。
hooks: {
"email:beforeSend": async (event, ctx) => {
return {
...event.message,
text: event.message.text + "\n\n—Sent from My Site",
};
},
}
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
投遞成功後的即發即忘鉤子。錯誤會被記錄但不會傳播。
hooks: {
"email:afterSend": async (event, ctx) => {
await ctx.kv.set(`email:log:${Date.now()}`, {
to: event.message.to,
subject: event.message.subject,
});
},
}
留言鉤子
留言鉤子按順序執行:comment:beforeCreate,然後 comment:moderate,然後 comment:afterCreate。comment:afterModerate 鉤子在管理員更改留言狀態時單獨觸發。
comment:beforeCreate
能力: users:read
留言儲存前的中介軟體鉤子。用於豐富、驗證或拒絕留言。
hooks: {
"comment:beforeCreate": async (event, ctx) => {
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: { /* 同 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
留言儲存後的即發即忘鉤子。用於通知。
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
管理員手動更改留言狀態時的即發即忘鉤子。
Event
interface CommentAfterModerateEvent {
comment: { id: string; /* ... */ };
previousStatus: string;
newStatus: string;
moderator: { id: string; name: string | null };
}
頁面鉤子
頁面鉤子在渲染公開頁面時執行。允許外掛注入中繼資料和腳本。
page:metadata
能力: 無需
向頁面 head 貢獻 meta 標籤、Open Graph 屬性、JSON-LD 結構化資料或 link 標籤。
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 欄位對貢獻進行去重 — 只使用給定 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;
};
鉤子配置
鉤子接受處理函式或配置物件:
hooks: {
// 簡單處理函式
"content:afterSave": async (event, ctx) => { ... },
// 帶配置
"content:beforeSave": {
priority: 50, // 較低的值先執行(預設: 100)
timeout: 10000, // 最大執行時間 ms(預設: 5000)
dependencies: [], // 在這些外掛之後執行
errorPolicy: "abort", // "continue" 或 "abort"(預設)
handler: async (event, ctx) => { ... },
},
}
配置選項
| 選項 | 型別 | 預設值 | 說明 |
|---|---|---|---|
priority | number | 100 | 執行順序(越低越早) |
timeout | number | 5000 | 最大執行時間(毫秒) |
dependencies | string[] | [] | 必須先執行的外掛 ID |
errorPolicy | string | "abort" | "continue" 忽略錯誤 |
exclusive | boolean | false | 只有一個外掛可以是活動提供者(用於 email:deliver、comment:moderate 等提供者模式鉤子) |
外掛上下文
所有鉤子都會收到一個可存取外掛 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;
}
能力要求和方法詳情請參閱外掛概覽 — 外掛上下文。
錯誤處理
鉤子中的錯誤根據 errorPolicy 進行記錄和處理:
"abort"(預設)— 停止執行,如適用則回滾交易"continue"— 記錄錯誤並繼續下一個鉤子
hooks: {
"content:beforeSave": {
errorPolicy: "continue",
handler: async (event, ctx) => {
try {
await ctx.http?.fetch("https://api.example.com/validate");
} catch (error) {
ctx.log.warn("Validation service unavailable", error);
}
},
},
}
執行順序
鉤子按此順序執行:
- 按
priority排序(升序) - 有
dependencies的外掛在其相依性之後執行 - 相同優先順序內,順序是確定性的但未指定
// 這個先執行(優先順序 10)
{ priority: 10, handler: ... }
// 這個第二執行(優先順序 50)
{ priority: 50, handler: ... }
// 這個最後執行(預設優先順序 100)
{ handler: ... }