Route API

In questa pagina

I plugin possono esporre route API per la loro interfaccia admin e le integrazioni esterne. Le route vengono montate sotto /_emdash/api/plugins/<slug>/<route-name> (lo <slug> è il campo slug da emdash-plugin.jsonc — esposto al runtime come ctx.plugin.id) e vengono eseguite all’interno del runtime sandbox con lo stesso PluginContext che ricevono gli hook.

Questa pagina copre i plugin sandboxed. 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 nell’export di default di src/plugin.ts:

import type { SandboxedPlugin } from "emdash/plugin";
import { z } from "astro/zod";

export default {
	routes: {
		status: {
			handler: async (_routeCtx, ctx) => {
				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) => {
				const { formId, limit, cursor } = routeCtx.input;

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

				return result;
			},
		},
	},
} satisfies SandboxedPlugin;

satisfies SandboxedPlugin deduce routeCtx e ctx — nessuna annotazione di parametri necessaria. Gli handler di route sandboxed prendono due argomenti: (routeCtx, ctx).

  • routeCtx contiene dati a forma di richiesta: { input, request, requestMeta }.
  • ctx è lo stesso PluginContext che ottieni negli hook — ctx.storage, ctx.kv, ctx.content, ctx.http, ctx.log, ecc.

URL delle route

Le route vengono montate a /_emdash/api/plugins/<slug>/<route-name>. I nomi delle route possono includere slash per percorsi nidificati.

ID del pluginNome della 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 per 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 cambiano stato sulle route private richiedono anche l’header CSRF X-EmDash-Request: 1 (l’hook usePluginAPI() dell’interfaccia admin lo invia automaticamente; i chiamanti esterni autenticati con cookie devono impostarlo da soli; le richieste autenticate con token sono esentate).

Per escludere una route da autenticazione e CSRF, contrassegnala con 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 nella busta standard di EmDash ({ success: true, data: <your value> }) e lo serve come application/json.

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

Errori

Lancia 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 invece di 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

routeCtx.request è un SandboxedRequest: un record portabile { url, method, headers } che si comporta in modo identico in-process e all’interno di un isolate. headers è un Record<string, string> indicizzato per nome di header in minuscolo — indicizzalo per il nome in minuscolo o itera con Object.entries. url è una stringa, quindi new URL(request.url) analizza i parametri di query. routeCtx.requestMeta contiene IP, user agent e dati geo normalizzati tra le piattaforme quando disponibili.

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

	const auth = request.headers["authorization"]; // lowercased key, no .get()
	const url = new URL(request.url);
	const page = url.searchParams.get("page");

	ctx.log.info("Request", { meta: requestMeta });

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

Pattern comuni

Impostazioni tramite KV

I plugin sandboxed leggono e scrivono le impostazioni attraverso lo store KV, convenzionalmente sotto un prefisso settings:. Il form settingsSchema autogenerato è solo per nativi — per i plugin sandboxed, esponi la lettura/scrittura attraverso le 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

Fai il proxy di una richiesta a un servizio esterno tramite ctx.http (richiede la capability 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 le route dall’interfaccia admin

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 le 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": "user@example.com"}'

Riferimento del contesto di route

// Ciò che ricevono gli handler di route sandboxed come loro due argomenti

interface SandboxedRequest {
	url: string;
	method: string;
	headers: Record<string, string>; // lowercased keys
}

interface SandboxedRouteContext {
	input: unknown; // narrow with the `input` Zod schema at the route level
	request: SandboxedRequest;
	requestMeta?: unknown;
}

interface PluginContext {
	plugin: { id: string; version: string };
	storage: PluginStorage;
	kv: KVAccess;
	log: LogAccess;
	site: SiteInfo;
	url(path: string): string;
	cron?: CronAccess;
	content?: ContentAccess;       // when content:read or content:write declared
	media?: MediaAccess;           // when media:read or media:write declared
	http?: HttpAccess;             // when network:request declared
	users?: UserAccess;            // when users:read declared
	email?: EmailAccess;           // when email:send declared and provider configured
}

I plugin nativi ricevono un singolo argomento RouteContext che combina i due — vedi Creare plugin nativi se stai seguendo quella strada.