跳至主内容
版本:9.x

HTTP RPC 规范

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

方法与类型映射

HTTP MethodMappingNotes
GET.query()Input JSON-stringified in query param.
e.g. myQuery?input=${encodeURIComponent(JSON.stringify(input))
POST.mutation()Input as POST body.
n/a.subscription()Subscriptions are not supported in HTTP transport

批量处理

批量处理时,我们使用数据加载器将同类型的所有并行过程调用合并到单个请求中。

  • 被调用过程名称通过逗号 (,) 组合在 pathname

  • 输入参数通过名为 input 的查询参数传递,其结构为 Record<number, unknown>

  • 需要额外传递 batch=1 查询参数

  • 当响应包含不同状态时返回 207 Multi-Status(例如部分调用成功部分失败时)

批量处理请求示例

假设在 /api/trpc 暴露的路由如下:

server/router.ts
tsx
export const appRouter = trpc
.router<Context>()
.query('postById', {
input: String,
async resolve({ input, ctx }) {
const post = await ctx.post.findUnique({
where: { id: input },
});
return post;
},
})
.query('relatedPosts', {
input: String,
async resolve({ ctx, input }) {
const posts = await ctx.findRelatedPostsById(input);
return posts;
},
});
server/router.ts
tsx
export const appRouter = trpc
.router<Context>()
.query('postById', {
input: String,
async resolve({ input, ctx }) {
const post = await ctx.post.findUnique({
where: { id: input },
});
return post;
},
})
.query('relatedPosts', {
input: String,
async resolve({ ctx, input }) {
const posts = await ctx.findRelatedPostsById(input);
return posts;
},
});

在 React 组件中定义的两个查询如下:

MyComponent.tsx
tsx
export function MyComponent() {
const post1 = trpc.useQuery(['postById', '1']);
const relatedPosts = trpc.useQuery(['relatedPosts', '1']);
return (
<pre>
{JSON.stringify(
{
post1: post1.data ?? null,
relatedPosts: relatedPosts.data ?? null,
},
null,
4,
)}
</pre>
);
}
MyComponent.tsx
tsx
export function MyComponent() {
const post1 = trpc.useQuery(['postById', '1']);
const relatedPosts = trpc.useQuery(['relatedPosts', '1']);
return (
<pre>
{JSON.stringify(
{
post1: post1.data ?? null,
relatedPosts: relatedPosts.data ?? null,
},
null,
4,
)}
</pre>
);
}

上述操作将产生单次 HTTP 调用,数据如下:

Location propertyValue
pathname/api/trpc/postById,relatedPosts
search?batch=1&input=%7B%220%22%3A%221%22%2C%221%22%3A%221%22%7D *

*) 上图中的 input 是以下操作的结果:

ts
encodeURIComponent(
JSON.stringify({
0: '1', // <-- input for `postById`
1: '1', // <-- input for `relatedPosts`
}),
);
ts
encodeURIComponent(
JSON.stringify({
0: '1', // <-- input for `postById`
1: '1', // <-- input for `relatedPosts`
}),
);

批量处理响应示例

Example output from server
json
[
// result for `postById`
{
"id": null,
"result": {
"type": "data",
"data": {
"id": "1",
"title": "Hello tRPC",
"body": "..."
// ...
}
}
},
// result for `relatedPosts`
{
"id": null,
"result": {
"type": "data",
"data": [
/* ... */
]
}
}
]
json
[
// result for `postById`
{
"id": null,
"result": {
"type": "data",
"data": {
"id": "1",
"title": "Hello tRPC",
"body": "..."
// ...
}
}
},
// result for `relatedPosts`
{
"id": null,
"result": {
"type": "data",
"data": [
/* ... */
]
}
}
]

HTTP 响应规范

为确保规范不受传输层限制,我们尽可能遵循 JSON-RPC 2.0 标准。

成功响应

Example JSON Response
json
{
"id": null,
"result": {
"type": "data",
"data": {
"id": "1",
"title": "Hello tRPC",
"body": "..."
}
}
}
json
{
"id": null,
"result": {
"type": "data",
"data": {
"id": "1",
"title": "Hello tRPC",
"body": "..."
}
}
}
ts
{
id: null;
result: {
type: 'data';
data: TOutput; // output from procedure
}
}
ts
{
id: null;
result: {
type: 'data';
data: TOutput; // output from procedure
}
}

错误响应

Example JSON Response
json
[
{
"id": null,
"error": {
"json": {
"message": "Something went wrong",
"code": -32600, // JSON-RPC 2.0 code
"data": {
// Extra, customizable, meta data
"code": "INTERNAL_SERVER_ERROR",
"httpStatus": 500,
"stack": "...",
"path": "post.add"
}
}
}
}
]
json
[
{
"id": null,
"error": {
"json": {
"message": "Something went wrong",
"code": -32600, // JSON-RPC 2.0 code
"data": {
// Extra, customizable, meta data
"code": "INTERNAL_SERVER_ERROR",
"httpStatus": 500,
"stack": "...",
"path": "post.add"
}
}
}
}
]

  • 尽可能从抛出错误传播 HTTP 状态码

  • 当响应包含不同状态时返回 207 Multi-Status(例如部分调用成功部分失败时)

  • 关于错误处理及自定义方法详见错误格式化

错误代码与 HTTP 状态映射

ts
PARSE_ERROR: 400,
BAD_REQUEST: 400,
NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
TIMEOUT: 408,
CONFLICT: 409,
CLIENT_CLOSED_REQUEST: 499,
PRECONDITION_FAILED: 412,
PAYLOAD_TOO_LARGE: 413,
METHOD_NOT_SUPPORTED: 405,
ts
PARSE_ERROR: 400,
BAD_REQUEST: 400,
NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
TIMEOUT: 408,
CONFLICT: 409,
CLIENT_CLOSED_REQUEST: 499,
PRECONDITION_FAILED: 412,
PAYLOAD_TOO_LARGE: 413,
METHOD_NOT_SUPPORTED: 405,

错误代码与 JSON-RPC 2.0 映射

Available codes & JSON-RPC code
ts
/**
* JSON-RPC 2.0 Error codes
*
* `-32000` to `-32099` are reserved for implementation-defined server-errors.
* For tRPC we're copying the last digits of HTTP 4XX errors.
*/
export const TRPC_ERROR_CODES_BY_KEY = {
/**
* Invalid JSON was received by the server.
* An error occurred on the server while parsing the JSON text.
*/
PARSE_ERROR: -32700,
/**
* The JSON sent is not a valid Request object.
*/
BAD_REQUEST: -32600, // 400
/**
* Internal JSON-RPC error.
*/
INTERNAL_SERVER_ERROR: -32603,
// Implementation specific errors
UNAUTHORIZED: -32001, // 401
FORBIDDEN: -32003, // 403
NOT_FOUND: -32004, // 404
METHOD_NOT_SUPPORTED: -32005, // 405
TIMEOUT: -32008, // 408
CONFLICT: -32009, // 409
PRECONDITION_FAILED: -32012, // 412
PAYLOAD_TOO_LARGE: -32013, // 413
CLIENT_CLOSED_REQUEST: -32099, // 499
} as const;
ts
/**
* JSON-RPC 2.0 Error codes
*
* `-32000` to `-32099` are reserved for implementation-defined server-errors.
* For tRPC we're copying the last digits of HTTP 4XX errors.
*/
export const TRPC_ERROR_CODES_BY_KEY = {
/**
* Invalid JSON was received by the server.
* An error occurred on the server while parsing the JSON text.
*/
PARSE_ERROR: -32700,
/**
* The JSON sent is not a valid Request object.
*/
BAD_REQUEST: -32600, // 400
/**
* Internal JSON-RPC error.
*/
INTERNAL_SERVER_ERROR: -32603,
// Implementation specific errors
UNAUTHORIZED: -32001, // 401
FORBIDDEN: -32003, // 403
NOT_FOUND: -32004, // 404
METHOD_NOT_SUPPORTED: -32005, // 405
TIMEOUT: -32008, // 408
CONFLICT: -32009, // 409
PRECONDITION_FAILED: -32012, // 412
PAYLOAD_TOO_LARGE: -32013, // 413
CLIENT_CLOSED_REQUEST: -32099, // 499
} as const;

深入探索

可通过以下 TypeScript 定义获取更多实现细节: