Riferimento Hook

In questa pagina

Gli hook consentono ai plugin di intercettare e modificare il comportamento di EmDash in punti specifici del ciclo di vita di contenuti, media, email, commenti e pagine.

Panoramica degli hook

La seguente tabella elenca ogni hook, cosa lo attiva, cosa può modificare e se è esclusivo:

HookAttivatorePuò modificareEsclusivo
content:beforeSavePrima del salvataggio del contenutoDati contenutoNo
content:afterSaveDopo il salvataggio del contenutoNienteNo
content:beforeDeletePrima dell’eliminazione del contenutoPuò annullareNo
content:afterDeleteDopo l’eliminazione del contenutoNienteNo
media:beforeUploadPrima del caricamento fileMetadati fileNo
media:afterUploadDopo il caricamento fileNienteNo
cronAttività pianificata viene eseguitaNienteNo
email:beforeSendPrima dell’invio emailMessaggio, può annullareNo
email:deliverConsegnare email tramite trasportoNiente
email:afterSendDopo l’invio email riuscitoNienteNo
comment:beforeCreatePrima di salvare commentoCommento, può annullareNo
comment:moderateDecidere stato approvazione commentoStato
comment:afterCreateDopo aver salvato commentoNienteNo
comment:afterModerateDopo che admin cambia stato commentoNienteNo
page:metadataRendering head pagina pubblicaContribuire tagNo
page:fragmentsRendering body pagina pubblicaIniettare scriptNo
plugin:installQuando il plugin viene installatoNienteNo
plugin:activateQuando il plugin viene abilitatoNienteNo
plugin:deactivateQuando il plugin viene disabilitatoNienteNo
plugin:uninstallQuando il plugin viene rimossoNienteNo

Hook dei Contenuti

content:beforeSave

Viene eseguito prima di salvare il contenuto nel database. Usare per validare, trasformare o arricchire il contenuto.

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
}

Valore di ritorno

  • Restituire oggetto contenuto modificato per applicare le modifiche
  • Restituire void per passare senza modifiche

content:afterSave

Viene eseguito dopo aver salvato il contenuto. Usare per effetti collaterali come notifiche, invalidazione cache o sincronizzazione esterna.

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

Valore di ritorno

Nessun valore di ritorno previsto.

content:beforeDelete

Viene eseguito prima di eliminare il contenuto. Usare per validare l’eliminazione o impedirla.

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
}

Valore di ritorno

  • Restituire false per annullare l’eliminazione
  • Restituire true o void per permettere

content:afterDelete

Viene eseguito dopo aver eliminato il contenuto. Usare per attività di pulizia.

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

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

Hook dei Media

media:beforeUpload

Viene eseguito prima di caricare un file. Usare per validare, rinominare o rifiutare file.

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

Valore di ritorno

  • Restituire metadati file modificati per applicare le modifiche
  • Restituire void per passare senza modifiche
  • Lanciare eccezione per rifiutare il caricamento

media:afterUpload

Viene eseguito dopo aver caricato un file. Usare per elaborazione, miniature o estrazione di metadati.

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 del Ciclo di Vita

plugin:install

Viene eseguito quando un plugin viene installato per la prima volta. Usare per configurazione iniziale, creazione di collezioni di archiviazione o dati di seed.

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

Viene eseguito quando un plugin viene abilitato (dopo installazione o riattivazione).

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

plugin:deactivate

Viene eseguito quando un plugin viene disabilitato.

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

plugin:uninstall

Viene eseguito quando un plugin viene rimosso. Usare per la pulizia.

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
}

Hook Cron

cron

Attivato quando un’attività pianificata viene eseguita. Pianificare attività con 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 Email

Gli hook email vengono eseguiti in ordine: email:beforeSend, poi email:deliver, poi email:afterSend.

email:beforeSend

Capacità: hooks.email-events:register

Hook middleware che viene eseguito prima della consegna. Trasformare messaggi o annullare la consegna.

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

Valore di ritorno

  • Restituire messaggio modificato per trasformare
  • Restituire false per annullare la consegna
  • Restituire void per passare senza modifiche

email:deliver

Capacità: hooks.email-transport:register | Esclusivo:

Il provider di trasporto. Solo un plugin può consegnare email. Responsabile dell’invio effettivo del messaggio tramite un servizio email.

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

email:afterSend

Capacità: hooks.email-events:register

Hook fire-and-forget dopo consegna riuscita. Gli errori vengono registrati ma non si propagano.

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

Hook dei Commenti

Gli hook dei commenti vengono eseguiti in ordine: comment:beforeCreate, poi comment:moderate, poi comment:afterCreate. L’hook comment:afterModerate viene attivato separatamente quando un admin cambia lo stato di un commento.

comment:beforeCreate

Capacità: users:read

Hook middleware prima di salvare un commento. Arricchire, validare o rifiutare commenti.

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

Valore di ritorno

  • Restituire evento modificato per trasformare
  • Restituire false per rifiutare
  • Restituire void per passare

comment:moderate

Capacità: users:read | Esclusivo:

Decidere se un commento è approvato, in sospeso o spam. Solo un provider di moderazione è attivo.

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

Valore di ritorno

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

comment:afterCreate

Capacità: users:read

Hook fire-and-forget dopo aver salvato un commento. Usare per notifiche.

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

Capacità: users:read

Hook fire-and-forget quando un admin cambia manualmente lo stato di un commento.

Event

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

Hook delle Pagine

Gli hook delle pagine vengono eseguiti durante il rendering delle pagine pubbliche. Consentono ai plugin di iniettare metadati e script.

page:metadata

Capacità: Nessuna richiesta

Contribuire meta tag, proprietà Open Graph, dati strutturati JSON-LD o tag di link all’head della pagina.

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 } },
    ];
  },
}

Tipi di Contributo

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

Il campo key deduplica i contributi — viene usato solo l’ultimo contributo con una chiave data.

page:fragments

Capacità: hooks.page-fragments:register

Iniettare script o HTML nelle pagine. Disponibile solo per plugin nativi.

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";`,
      },
    ];
  },
}

Tipi di Contributo

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

Configurazione Hook

Gli hook accettano una funzione handler o un oggetto di configurazione:

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) => { ... },
  },
}

Opzioni di Configurazione

OpzioneTipoPredefinitoDescrizione
prioritynumber100Ordine di esecuzione (più basso = prima)
timeoutnumber5000Tempo massimo di esecuzione in millisecondi
dependenciesstring[][]ID plugin che devono essere eseguiti per primi
errorPolicystring"abort""continue" per ignorare gli errori
exclusivebooleanfalseSolo un plugin può essere il provider attivo (per hook con pattern provider come email:deliver, comment:moderate)

Contesto Plugin

Tutti gli hook ricevono un oggetto di contesto con accesso alle API del plugin:

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

Vedere Panoramica Plugin — Contesto Plugin per requisiti di capacità e dettagli dei metodi.

Gestione degli Errori

Gli errori negli hook vengono registrati e gestiti in base a errorPolicy:

  • "abort" (predefinito) — Interrompere l’esecuzione, annullare la transazione se applicabile
  • "continue" — Registrare l’errore e continuare all’hook successivo
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);
      }
    },
  },
}

Ordine di Esecuzione

Gli hook vengono eseguiti in questo ordine:

  1. Ordinati per priority (crescente)
  2. I plugin con dependencies vengono eseguiti dopo le loro dipendenze
  3. All’interno della stessa priorità, l’ordine è deterministico ma non specificato
// This runs first (priority 10)
{ priority: 10, handler: ... }

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

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