플러그인 API 라우트
플러그인은 관리자 UI 컴포넌트나 외부 통합을 위해 API 라우트를 노출할 수 있습니다. 라우트는 전체 플러그인 컨텍스트를 수신하며 스토리지, KV, 콘텐츠, 미디어에 접근할 수 있습니다.
라우트 정의하기
섹션 제목: “라우트 정의하기”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
섹션 제목: “라우트 URL”라우트는 /_emdash/api/plugins/<plugin-id>/<route-name>에 마운트됩니다:
| 플러그인 ID | 라우트 이름 | URL |
|---|---|---|
forms | status | /_emdash/api/plugins/forms/status |
forms | submissions | /_emdash/api/plugins/forms/submissions |
seo | settings/save | /_emdash/api/plugins/seo/settings/save |
라우트 이름은 중첩 경로를 위해 슬래시를 포함할 수 있습니다.
라우트 핸들러
섹션 제목: “라우트 핸들러”핸들러는 플러그인 컨텍스트에 요청별 데이터가 추가된 RouteContext를 수신합니다:
interface RouteContext extends PluginContext { input: TInput; // Validated input (from body or query params) request: Request; // Original Request object}반환 값
섹션 제목: “반환 값”JSON으로 직렬화 가능한 모든 값을 반환하세요:
// Objectreturn { 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("항목을 찾을 수 없음"); // 반환: { "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 스키마를 사용하여 입력을 검증하고 파싱하세요:
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 오류를 반환합니다.
입력 소스
섹션 제목: “입력 소스”입력은 다음에서 파싱됩니다:
- POST/PUT/PATCH — 요청 본문 (JSON)
- GET/DELETE — URL 쿼리 매개변수
// POST /plugins/forms/create// Body: { "title": "Hello", "email": "user@example.com" }
// GET /plugins/forms/list?limit=20&status=pendingHTTP 메서드
섹션 제목: “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("허용되지 않는 메서드", { status: 405 }); } } }}요청 접근
섹션 제목: “요청 접근”전체 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 필요", { status: 405 }); }
// 본문 (입력 스키마를 사용하지 않는 경우) 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 프록시
섹션 제목: “외부 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 오류: ${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("동기화 완료", { synced, duration });
return { success: true, synced, duration, }; }; }}관리자 UI에서 라우트 호출하기
섹션 제목: “관리자 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 requestcurl 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": "user@example.com"}'경로 컨텍스트 참조
섹션 제목: “경로 컨텍스트 참조”interface RouteContext<TInput = unknown> extends PluginContext { /** Validated input from request body or query params */ input: TInput;
/** 원본 요청 객체 */ request: Request;
/** 플러그인 메타데이터 */ plugin: { id: string; version: string };
/** 플러그인 스토리지 컬렉션 */ storage: Record<string, StorageCollection>;
/** 키-값 저장소 */ kv: KVAccess;
/** 콘텐츠 접근 (능력 선언 시) */ content?: ContentAccess;
/** 미디어 접근 (능력 선언 시) */ media?: MediaAccess;
/** HTTP 클라이언트 (능력 선언 시) */ http?: HttpAccess;
/** 구조화된 로거 */ log: LogAccess;}