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