> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # createRoute() `createRoute()` 函数使用 Zod 验证创建类型安全的路由。为服务器适配器配置 `openapiPath` 后,它会根据提供的 Zod schema 生成 OpenAPI schema 条目。 ## 导入 ```typescript import { createRoute } from '@mastra/server/server-adapter' ``` ## 签名 ```typescript function createRoute( config: RouteConfig, ): ServerRoute ``` ## 参数 **method** (`'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'`): HTTP 方法 **path** (`string`): 带有可选参数的路由路径(例如,/api/items/:id) **responseType** (`'json' | 'stream'`): 响应格式。内部路由可能使用额外类型(datastream-response、mcp-http、mcp-sse)。 **handler** (`ServerRouteHandler`): 路由处理函数 **pathParamSchema** (`ZodSchema`): 验证 URL 路径参数 **queryParamSchema** (`ZodSchema`): 验证查询字符串参数 **bodySchema** (`ZodSchema`): 验证请求正文 **responseSchema** (`ZodSchema`): 为 OpenAPI 记录响应结构 **streamFormat** (`'sse' | 'stream'`): 流格式(当 responseType 为 'stream' 时) **maxBodySize** (`number`): 以字节为单位覆盖默认正文大小限制 **summary** (`string`): OpenAPI 摘要 **description** (`string`): OpenAPI 描述 **tags** (`string[]`): OpenAPI 标签 **deprecated** (`boolean`): 将路由标记为已弃用 **onValidationError** (`(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined`): 此路由的自定义验证错误处理器。它会覆盖服务器级别的 onValidationError hook。返回 { status, body } 以自定义响应,或返回 undefined 以使用默认值。 ## 处理函数参数 Handler 会接收已验证的参数以及运行时上下文: ```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 } ``` ## 返回值 返回可通过适配器注册的 `ServerRoute` 对象。 ## 示例 ### 带路径参数的 GET 路由 ```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) }, }) ``` ### 带正文的 POST 路由 ```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 } }, }) ``` ### 使用强制转换的查询参数 ```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 } }, }) ``` ### 流式路由 ```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 }) }, }) ``` ### 自定义正文大小限制 ```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 模式 ### 用于可扩展性的透传 ```typescript const bodySchema = z .object({ required: z.string(), }) .passthrough() // Allow unknown fields ``` ### 日期强制转换 ```typescript const querySchema = z.object({ fromDate: z.coerce.date().optional(), toDate: z.coerce.date().optional(), }) ``` ### 联合类型 ```typescript const bodySchema = z.object({ messages: z.union([z.array(z.any()), z.string()]), }) ``` ## 错误处理 抛出带有 `status` 属性的错误,以从 Handler 返回特定的 HTTP 状态码。若使用 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 或框架无关的代码,抛出带有 `status` 属性的错误: ```typescript class HttpError extends Error { constructor( public status: number, message: string, ) { super(message) } } // In handler: throw new HttpError(404, `Agent '${agentId}' not found`) ``` 常见状态码: | 代码 | 含义 | | --- | ------- | | 400 | 错误请求 | | 401 | 未授权 | | 403 | 禁止访问 | | 404 | 未找到 | | 500 | 内部服务器错误 | ## 相关内容 - [服务器路由](https://mastra.zisheng.pro/reference/server/routes):默认 Mastra 路由 - [MastraServer](https://mastra.zisheng.pro/reference/server/mastra-server):服务器适配器类 - [服务器适配器](https://mastra.zisheng.pro/docs/server/server-adapters):使用适配器