본문으로 건너뛰기

경로 생성()

그만큼createRoute()함수는 Zod 검증을 통해 유형이 안전한 경로를 생성합니다. 때openapiPath서버 어댑터에 구성되면 제공된 Zod 스키마에서 OpenAPI 스키마 항목을 생성합니다.

수입
수입에 대한 직접 링크

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 설명

tags?:

string[]
OpenAPI 태그

deprecated?:

boolean
경로를 사용 중단으로 표시합니다

onValidationError?:

(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined
이 경로의 사용자 정의 유효성 검사 오류 핸들러입니다. 서버 수준의 onValidationError 훅을 재정의합니다. 응답을 사용자 정의하려면 { status, body }를 반환하고, 기본값을 사용하려면 undefined를 반환하세요.

핸들러 매개변수
핸들러 매개변수에 대한 직접 링크

핸들러는 검증된 매개변수와 런타임 컨텍스트를 수신합니다.

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 }
},
})

스키마 패턴
스키마 패턴에 대한 직접 링크

확장성을 위한 패스스루
확장성을 위한 패스스루에 대한 직접 링크

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()]),
})

오류 처리
오류 처리에 대한 직접 링크

핸들러에서 특정 HTTP 상태 코드를 반환하려면 status 속성이 있는 오류를 발생시키세요. Hono를 사용하는 경우 hono/http-exceptionHTTPException을 사용할 수 있습니다.

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 property:

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내부 서버 오류