Route API

In questa pagina

I plugin possono esporre route API per la loro interfaccia di amministrazione e integrazioni esterne. Le route sono montate sotto /_emdash/api/plugins/<plugin-id>/<route-name> e vengono eseguite all’interno del runtime sandbox con lo stesso PluginContext che ricevono gli hooks.

Questa pagina tratta i plugin sandboxed (formato standard). La superficie API per i plugin nativi è la stessa; l’unica differenza è la firma dell’handler — vedi la nota in Plugin nativi per i dettagli.

Definire le route

Dichiara le route in definePlugin() dal tuo sandbox-entry.ts:

import { definePlugin } from "emdash";
import type { PluginContext } from "emdash";
import { z } from "astro/zod";

export default definePlugin({
	routes: {
		status: {
			handler: async (_routeCtx, ctx: PluginContext) => {
				return { ok: true, plugin: ctx.plugin.id };
			},
		},

		submissions: {
			input: z.object({
				formId: z.string().optional(),
				limit: z.number().default(50),
				cursor: z.string().optional(),
			}),
			handler: async (routeCtx, ctx: PluginContext) => {
				const { formId, limit, cursor } = routeCtx.input;

				const result = await ctx.storage.submissions.query({
					where: formId ? { formId } : undefined,
					orderBy: { createdAt: "desc" },
					limit,
					cursor,
				});

				return result;
			},
		},
	},
});

Gli handler delle route in formato standard accettano due argomenti: (routeCtx, ctx).

  • routeCtx contiene dati in forma di richiesta: { input, request, requestMeta }.
  • ctx è lo stesso PluginContext che ottieni all’interno degli hooks — ctx.storage, ctx.kv, ctx.content, ctx.http, ctx.log, ecc.

URL delle route

Le route sono montate a /_emdash/api/plugins/<plugin-id>/<route-name>. I nomi delle route possono includere barre per percorsi annidati.

ID pluginNome routeURL
formsstatus/_emdash/api/plugins/forms/status
formssubmissions/_emdash/api/plugins/forms/submissions
seosettings/save/_emdash/api/plugins/seo/settings/save
analyticsevents/recent/_emdash/api/plugins/analytics/events/recent

Autenticazione e CSRF

Le route dei plugin sono autenticate di default. Il dispatcher richiede una sessione (o un token con lo scope admin) prima di chiamare il tuo handler:

  • I metodi di lettura (GET, HEAD, OPTIONS) richiedono il permesso plugins:read.
  • I metodi di scrittura (POST, PUT, PATCH, DELETE) richiedono plugins:manage.
  • I metodi che modificano lo stato sulle route private richiedono anche l’header CSRF X-EmDash-Request: 1 (l’hook usePluginAPI() dell’interfaccia di amministrazione lo invia automaticamente; i chiamanti esterni autenticati tramite cookie devono impostarlo da soli; le richieste autenticate tramite token ne sono esentate).

Per escludere una route dall’autenticazione e CSRF, contrassegnala come public: true:

routes: {
	track: {
		public: true,
		input: z.object({ event: z.string() }),
		handler: async (routeCtx, ctx) => {
			ctx.log.info("Tracked", { event: routeCtx.input.event });
			return { ok: true };
		},
	},
},

Validazione dell’input

input accetta uno schema Zod. Il dispatcher analizza il corpo della richiesta (POST/PUT/PATCH) o la query string (GET/DELETE), lo valida e passa il risultato tipizzato al tuo handler come routeCtx.input. Un input non valido restituisce un 400 prima che il tuo handler venga eseguito.

routes: {
	create: {
		input: z.object({
			title: z.string().min(1).max(200),
			email: z.string().email(),
			priority: z.enum(["low", "medium", "high"]).default("medium"),
			tags: z.array(z.string()).optional(),
		}),
		handler: async (routeCtx, ctx) => {
			const { title, email, priority, tags } = routeCtx.input;

			await ctx.storage.items.put(`item_${Date.now()}`, {
				title,
				email,
				priority,
				tags: tags ?? [],
				createdAt: new Date().toISOString(),
			});

			return { success: true };
		},
	},
},

Valori di ritorno

Restituisci qualsiasi valore serializzabile in JSON. Il dispatcher lo avvolge nell’envelope standard di EmDash ({ success: true, data: <il tuo valore> }) e lo serve come application/json.

return { id: "abc", count: 42 };  // avvolto in { success: true, data: { id, count } }
return [1, 2, 3];                 // avvolto in { success: true, data: [1, 2, 3] }

Errori

Lancia un errore per restituire una risposta di errore. Qualsiasi cosa che non sia un errore di plugin noto restituisce un messaggio generico — le eccezioni interne sono mascherate anziché far trapelare stack trace o errori di database:

handler: async (routeCtx, ctx) => {
	const item = await ctx.storage.items.get(routeCtx.input.id);
	if (!item) {
		throw new Error("Item not found");
	}
	return item;
},

Per un codice di stato specifico, lancia una Response:

handler: async (routeCtx, ctx) => {
	const item = await ctx.storage.items.get(routeCtx.input.id);
	if (!item) {
		throw new Response(JSON.stringify({ error: "Not found" }), {
			status: 404,
			headers: { "Content-Type": "application/json" },
		});
	}
	return item;
},

Metodi HTTP

Le route rispondono a tutti i metodi. Ramifica su routeCtx.request.method se hai bisogno di un comportamento per metodo:

routes: {
	item: {
		input: z.object({ id: z.string() }),
		handler: async (routeCtx, ctx) => {
			const { id } = routeCtx.input;

			switch (routeCtx.request.method) {
				case "GET":
					return await ctx.storage.items.get(id);
				case "DELETE":
					await ctx.storage.items.delete(id);
					return { deleted: true };
				default:
					throw new Response("Method not allowed", { status: 405 });
			}
		},
	},
},

Accesso alla richiesta

L’oggetto Request completo è disponibile come routeCtx.request per header, accesso grezzo al corpo e parsing degli URL. routeCtx.requestMeta contiene IP, user agent e dati geo normalizzati tra le piattaforme.

handler: async (routeCtx, ctx) => {
	const { request, requestMeta } = routeCtx;

	const auth = request.headers.get("Authorization");
	const url = new URL(request.url);
	const page = url.searchParams.get("page");

	ctx.log.info("Request", { ip: requestMeta.ip, ua: requestMeta.userAgent });

	if (request.method !== "POST") {
		throw new Response("POST required", { status: 405 });
	}
},

Pattern comuni

Impostazioni tramite KV

I plugin sandboxed leggono e scrivono le impostazioni tramite lo store KV, convenzionalmente sotto un prefisso settings:. Il form settingsSchema generato automaticamente è solo per nativi — per i plugin sandboxed, esponi la lettura/scrittura tramite route e renderizza il form in Block Kit.

routes: {
	settings: {
		handler: async (_routeCtx, ctx) => {
			const settings = await ctx.kv.list("settings:");
			const result: Record<string, unknown> = {};
			for (const entry of settings) {
				result[entry.key.replace("settings:", "")] = entry.value;
			}
			return result;
		},
	},

	"settings/save": {
		input: z.object({
			enabled: z.boolean().optional(),
			apiKey: z.string().optional(),
			maxItems: z.number().optional(),
		}),
		handler: async (routeCtx, ctx) => {
			for (const [key, value] of Object.entries(routeCtx.input)) {
				if (value !== undefined) {
					await ctx.kv.set(`settings:${key}`, value);
				}
			}
			return { success: true };
		},
	},
},

Lista paginata

Restituisci una paginazione basata su cursore da una query di storage — la forma della risposta corrisponde a quella usata dal resto di EmDash:

routes: {
	list: {
		input: z.object({
			limit: z.number().min(1).max(100).default(50),
			cursor: z.string().optional(),
			status: z.string().optional(),
		}),
		handler: async (routeCtx, ctx) => {
			const { limit, cursor, status } = routeCtx.input;

			const result = await ctx.storage.items.query({
				where: status ? { status } : undefined,
				orderBy: { createdAt: "desc" },
				limit,
				cursor,
			});

			return {
				items: result.items.map((item) => ({ id: item.id, ...item.data })),
				cursor: result.cursor,
				hasMore: result.hasMore,
			};
		},
	},
},

Proxy API esterna

Inoltra una richiesta a un servizio esterno tramite ctx.http (richiede la capacità network:request e una voce in allowedHosts):

routes: {
	forecast: {
		input: z.object({ city: z.string() }),
		handler: async (routeCtx, ctx) => {
			if (!ctx.http) throw new Error("Network capability not granted");

			const apiKey = await ctx.kv.get<string>("settings:apiKey");
			if (!apiKey) throw new Error("API key not configured");

			const response = await ctx.http.fetch(
				`https://api.weather.example.com/forecast?city=${routeCtx.input.city}`,
				{ headers: { "X-API-Key": apiKey } },
			);

			if (!response.ok) {
				throw new Error(`Weather API error: ${response.status}`);
			}
			return response.json();
		},
	},
},

Chiamare route dall’interfaccia di amministrazione

Usa usePluginAPI() dal pacchetto admin — aggiunge automaticamente l’header CSRF X-EmDash-Request e il prefisso dell’ID del plugin:

import { usePluginAPI } from "@emdash-cms/admin";

function SettingsPage() {
	const api = usePluginAPI();

	const handleSave = async (settings) => {
		await api.post("settings/save", settings);
	};

	const loadSettings = async () => {
		return api.get("settings");
	};
}

Chiamare route esternamente

Le route pubbliche sono chiamabili direttamente:

curl -X POST https://your-site.com/_emdash/api/plugins/forms/track \
  -H "Content-Type: application/json" \
  -d '{"event": "pageview"}'

Le route private necessitano di credenziali di sessione o un token API con lo scope admin:

curl -X POST https://your-site.com/_emdash/api/plugins/forms/create \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"title": "Hello", "email": "[email protected]"}'

Riferimento del contesto route

// Ciò che gli handler in formato standard ricevono come loro due argomenti

interface StandardRouteContext<TInput = unknown> {
	input: TInput;
	request: Request;
	requestMeta: { ip: string | null; userAgent: string | null; geo?: GeoData };
}

interface PluginContext {
	plugin: { id: string; version: string };
	storage: PluginStorage;
	kv: KVAccess;
	log: LogAccess;
	site: SiteInfo;
	url(path: string): string;
	cron?: CronAccess;
	content?: ContentAccess;       // quando viene dichiarato content:read o content:write
	media?: MediaAccess;           // quando viene dichiarato media:read o media:write
	http?: HttpAccess;             // quando viene dichiarato network:request
	users?: UserAccess;            // quando viene dichiarato users:read
	email?: EmailAccess;           // quando viene dichiarato email:send e il provider è configurato
}

I plugin nativi ricevono un singolo argomento RouteContext che combina entrambi — vedi Creare plugin nativi se stai percorrendo quella strada.