> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # createRoute() `createRoute()` function 會建立具 Zod 驗證的 type-safe route。在 server adapter 設定 `openapiPath` 後,它會從提供的 Zod schema 產生 OpenAPI schema 項目。 ## 匯入 ```typescript import { createRoute } from '@mastra/server/server-adapter' ``` ## Signature ```typescript function createRoute( config: RouteConfig, ): ServerRoute ``` ## 參數 **method** (`'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'`): HTTP method **path** (`string`): 包含可選參數的 route 路徑(例如 /api/items/:id) **responseType** (`'json' | 'stream'`): Response 格式。內部 route 可使用其他類型(datastream-response、mcp-http、mcp-sse)。 **handler** (`ServerRouteHandler`): Route handler function **pathParamSchema** (`ZodSchema`): 驗證 URL 路徑參數 **queryParamSchema** (`ZodSchema`): 驗證 query string 參數 **bodySchema** (`ZodSchema`): 驗證 request body **responseSchema** (`ZodSchema`): 記錄 OpenAPI 的 response shape **streamFormat** (`'sse' | 'stream'`): Stream 格式(當 responseType 為 'stream' 時) **maxBodySize** (`number`): 以 byte 為單位覆寫預設 body 大小限制 **summary** (`string`): OpenAPI summary **description** (`string`): OpenAPI description **tags** (`string[]`): OpenAPI tags **deprecated** (`boolean`): 將 route 標記為 deprecated **onValidationError** (`(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined`): 此 route 的自訂驗證錯誤 handler。會覆寫 server 層級的 onValidationError hook。傳回 { status, body } 可自訂 response,傳回 undefined 則使用預設值。 ## Handler 參數 Handler 會接收已驗證的參數及 runtime context: ```typescript handler: async params => { // From schemas (typed from Zod) params.id // From pathParamSchema params.filter // From queryParamSchema params.name // From bodySchema // Runtime context (always available) params.mastra // Mastra instance params.requestContext // Request-scoped context params.tools // Available tools params.abortSignal // Request cancellation signal params.taskStore // A2A task storage } ``` ## 傳回值 傳回可向 adapter 註冊的 `ServerRoute` object。 ## 範例 ### 包含路徑參數的 GET route ```typescript import { createRoute } from '@mastra/server/server-adapter' import { z } from 'zod' const getAgent = createRoute({ method: 'GET', path: '/api/agents/:agentId', responseType: 'json', pathParamSchema: z.object({ agentId: z.string(), }), responseSchema: z.object({ name: z.string(), description: z.string().optional(), }), summary: 'Get agent by ID', tags: ['Agents'], handler: async ({ agentId, mastra }) => { return mastra.getAgent(agentId) }, }) ``` ### 包含 body 的 POST route ```typescript const createItem = createRoute({ method: 'POST', path: '/api/items', responseType: 'json', bodySchema: z.object({ name: z.string(), value: z.number(), }), responseSchema: z.object({ id: z.string(), name: z.string(), value: z.number(), }), handler: async ({ name, value, mastra }) => { // name and value are typed from bodySchema return { id: 'new-id', name, value } }, }) ``` ### 具 coercion 的 query 參數 ```typescript const listItems = createRoute({ method: 'GET', path: '/api/items', responseType: 'json', queryParamSchema: z.object({ page: z.coerce.number().default(0), limit: z.coerce.number().default(50), enabled: z.coerce.boolean().optional(), }), handler: async ({ page, limit, enabled, mastra }) => { // page, limit, enabled are typed and coerced return { items: [], page, limit } }, }) ``` ### Streaming route ```typescript const streamAgent = createRoute({ method: 'POST', path: '/api/agents/:agentId/stream', responseType: 'stream', streamFormat: 'sse', pathParamSchema: z.object({ agentId: z.string(), }), bodySchema: z.object({ messages: z.array(z.any()), }), handler: async ({ agentId, messages, mastra, abortSignal }) => { const agent = mastra.getAgent(agentId) return agent.stream(messages, { abortSignal }) }, }) ``` ### 自訂 body 大小限制 ```typescript const uploadRoute = createRoute({ method: 'POST', path: '/api/upload', responseType: 'json', maxBodySize: 50 * 1024 * 1024, // 50MB bodySchema: z.object({ file: z.string(), }), handler: async ({ file }) => { return { uploaded: true } }, }) ``` ## Schema 模式 ### 使用 passthrough 提供擴充能力 ```typescript const bodySchema = z .object({ required: z.string(), }) .passthrough() // Allow unknown fields ``` ### 日期 coercion ```typescript const querySchema = z.object({ fromDate: z.coerce.date().optional(), toDate: z.coerce.date().optional(), }) ``` ### Union 類型 ```typescript const bodySchema = z.object({ messages: z.union([z.array(z.any()), z.string()]), }) ``` ## 錯誤處理 拋出帶有 `status` property 的錯誤,可讓 handler 傳回指定的 HTTP status code。如使用 Hono,可以使用 `hono/http-exception` 的 `HTTPException`: ```typescript import { createRoute } from '@mastra/server/server-adapter' import { HTTPException } from 'hono/http-exception' const getAgent = createRoute({ method: 'GET', path: '/api/agents/:agentId', responseType: 'json', pathParamSchema: z.object({ agentId: z.string() }), handler: async ({ agentId, mastra }) => { const agent = mastra.getAgent(agentId) if (!agent) { throw new HTTPException(404, { message: `Agent '${agentId}' not found` }) } return agent }, }) ``` 對 Express 或不依賴 framework 的程式碼,請拋出帶有 `status` property 的錯誤: ```typescript class HttpError extends Error { constructor( public status: number, message: string, ) { super(message) } } // In handler: throw new HttpError(404, `Agent '${agentId}' not found`) ``` 常見 status code: | Code | 含義 | | ---- | ----------- | | 400 | 錯誤 request | | 401 | 未獲授權 | | 403 | 禁止存取 | | 404 | 找不到資源 | | 500 | Server 內部錯誤 | ## 相關內容 - [Server route](https://mastra.zisheng.pro/zh-HK/reference/server/routes):預設 Mastra route - [MastraServer](https://mastra.zisheng.pro/zh-HK/reference/server/mastra-server):Server adapter class - [Server adapter](https://mastra.zisheng.pro/zh-HK/docs/server/server-adapters):使用 adapter