createRoute()
createRoute() 函数使用 Zod 验证创建类型安全的路由。为服务器适配器配置 openapiPath 后,它会根据提供的 Zod schema 生成 OpenAPI schema 条目。
导入导入的直接链接
import { createRoute } from '@mastra/server/server-adapter'
签名签名的直接链接
function createRoute<TPath, TQuery, TBody, TResponse, TResponseType>(
config: RouteConfig<TPath, TQuery, TBody, TResponse, TResponseType>,
): 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 描述
deprecated?:
boolean
将路由标记为已弃用
onValidationError?:
(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined
此路由的自定义验证错误处理器。它会覆盖服务器级别的
onValidationError hook。返回 { status, body } 以自定义响应,或返回 undefined 以使用默认值。处理函数参数处理函数参数的直接链接
Handler 会接收已验证的参数以及运行时上下文:
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 路由带路径参数的 GET 路由的直接链接
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 路由带正文的 POST 路由的直接链接
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 }
},
})
使用强制转换的查询参数使用强制转换的查询参数的直接链接
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 }
},
})
流式路由流式路由的直接链接
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 })
},
})
自定义正文大小限制自定义正文大小限制的直接链接
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 模式Schema 模式的直接链接
用于可扩展性的透传用于可扩展性的透传的直接链接
const bodySchema = z
.object({
required: z.string(),
})
.passthrough() // Allow unknown fields
日期强制转换日期强制转换的直接链接
const querySchema = z.object({
fromDate: z.coerce.date().optional(),
toDate: z.coerce.date().optional(),
})
联合类型联合类型的直接链接
const bodySchema = z.object({
messages: z.union([z.array(z.any()), z.string()]),
})
错误处理错误处理的直接链接
抛出带有 status 属性的错误,以从 Handler 返回特定的 HTTP 状态码。若使用 Hono,可以使用 hono/http-exception 中的 HTTPException:
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 属性的错误:
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 | 内部服务器错误 |
相关内容相关内容的直接链接
- 服务器路由:默认 Mastra 路由
- MastraServer:服务器适配器类
- 服务器适配器:使用适配器