插件 API 路由

本页内容

插件可以为其后台 UI 组件或外部集成暴露 API 路由。路由接收完整的插件上下文,并可以访问存储、KV、内容和媒体。原生和沙盒插件都支持 API 路由。

定义路由

routes 对象中定义路由:

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

export default definePlugin({
	id: "forms",
	version: "1.0.0",

	storage: {
		submissions: {
			indexes: ["formId", "status", "createdAt"],
		},
	},

	routes: {
		// 简单路由
		status: {
			handler: async (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 (ctx) => {
				const { formId, limit, cursor } = ctx.input;

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

				return {
					items: result.items,
					cursor: result.cursor,
					hasMore: result.hasMore,
				};
			},
		},
	},
});

路由 URL

路由挂载在 /_emdash/api/plugins/<plugin-id>/<route-name>

插件 ID路由名称URL
formsstatus/_emdash/api/plugins/forms/status
formssubmissions/_emdash/api/plugins/forms/submissions
seosettings/save/_emdash/api/plugins/seo/settings/save

路由名称可以包含斜杠以创建嵌套路径。

路由处理器

处理器接收一个 RouteContext,其中包含插件上下文以及特定于请求的数据:

interface RouteContext extends PluginContext {
	input: TInput; // 验证后的输入(来自请求体或查询参数)
	request: Request; // 原始 Request 对象
}

返回值

返回任何可 JSON 序列化的值:

// 对象
return { success: true, data: items };

// 数组
return items;

// 原始值
return 42;

错误

抛出异常以返回错误响应:

handler: async (ctx) => {
	const item = await ctx.storage.items!.get(ctx.input.id);

	if (!item) {
		throw new Error("Item not found");
		// 返回:{ "error": "Item not found" } 状态码 500
	}

	return item;
};

对于自定义状态码,抛出 Response

handler: async (ctx) => {
	const item = await ctx.storage.items!.get(ctx.input.id);

	if (!item) {
		throw new Response(JSON.stringify({ error: "Not found" }), {
			status: 404,
			headers: { "Content-Type": "application/json" },
		});
	}

	return item;
};

输入验证

使用 Zod schema 验证和解析输入:

import { z } from "astro/zod";

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 (ctx) => {
      // ctx.input 已类型化和验证
      const { title, email, priority, tags } = ctx.input;

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

      return { success: true };
    }
  }
}

无效输入返回 400 错误,包含验证详情。

输入来源

输入解析自:

  1. POST/PUT/PATCH — 请求体(JSON)
  2. GET/DELETE — URL 查询参数
// POST /plugins/forms/create
// Body: { "title": "Hello", "email": "[email protected]" }

// GET /plugins/forms/list?limit=20&status=pending

HTTP 方法

路由响应所有 HTTP 方法。检查 ctx.request.method 以不同方式处理它们:

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

      switch (ctx.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 });
      }
    }
  }
}

访问 Request

完整的 Request 对象可用于高级用例:

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

	// 请求头
	const auth = request.headers.get("Authorization");

	// URL 参数
	const url = new URL(request.url);
	const page = url.searchParams.get("page");

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

	// 请求体(如果不使用 input schema)
	const body = await request.json();
};

常见模式

设置路由

暴露和更新插件设置:

routes: {
  settings: {
    handler: async (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 (ctx) => {
      const input = ctx.input;

      for (const [key, value] of Object.entries(input)) {
        if (value !== undefined) {
          await ctx.kv.set(`settings:${key}`, value);
        }
      }

      return { success: true };
    }
  }
}

分页列表

返回带有基于游标的导航的分页结果:

routes: {
  list: {
    input: z.object({
      limit: z.number().min(1).max(100).default(50),
      cursor: z.string().optional(),
      status: z.string().optional()
    }),
    handler: async (ctx) => {
      const { limit, cursor, status } = ctx.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
      };
    }
  }
}

外部 API 代理

代理请求到外部服务(需要 network:fetch 能力):

definePlugin({
	id: "weather",
	version: "1.0.0",

	capabilities: ["network:fetch"],
	allowedHosts: ["api.weather.example.com"],

	routes: {
		forecast: {
			input: z.object({
				city: z.string(),
			}),
			handler: async (ctx) => {
				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=${ctx.input.city}`,
					{
						headers: { "X-API-Key": apiKey },
					},
				);

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

				return response.json();
			},
		},
	},
});

操作端点

触发一次性操作:

routes: {
	sync: {
		handler: async (ctx) => {
			ctx.log.info("Starting sync...");

			const startTime = Date.now();
			let synced = 0;

			// 执行工作...
			const items = await fetchExternalItems(ctx);
			for (const item of items) {
				await ctx.storage.items!.put(item.id, item);
				synced++;
			}

			const duration = Date.now() - startTime;
			ctx.log.info("Sync complete", { synced, duration });

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

从后台 UI 调用路由

在后台组件中使用 usePluginAPI() 钩子:

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

该钩子会自动将插件 ID 添加到路由 URL 前缀。

外部调用路由

路由可通过其完整 URL 访问:

# GET 请求
curl https://your-site.com/_emdash/api/plugins/forms/submissions?limit=10

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

路由上下文参考

interface RouteContext<TInput = unknown> extends PluginContext {
	/** 来自请求体或查询参数的验证输入 */
	input: TInput;

	/** 原始请求对象 */
	request: Request;

	/** 插件元数据 */
	plugin: { id: string; version: string };

	/** 插件存储集合 */
	storage: Record<string, StorageCollection>;

	/** 键值存储 */
	kv: KVAccess;

	/** 内容访问(如果声明了能力) */
	content?: ContentAccess;

	/** 媒体访问(如果声明了能力) */
	media?: MediaAccess;

	/** HTTP 客户端(如果声明了能力) */
	http?: HttpAccess;

	/** 结构化日志记录器 */
	log: LogAccess;
}