HTTP RPC 规范
方法 <-> 类型映射
HTTP 方法 | 映射 | 备注 |
---|---|---|
GET | .query() | 输入 JSON 字符串化在查询参数中。 例如 myQuery?input=${encodeURIComponent(JSON.stringify(input))} |
POST | .mutation() | 输入作为 POST 主体。 |
n/a | .subscription() | 订阅在 HTTP 传输中不受支持 |
访问嵌套过程
嵌套过程由点号分隔,因此对下面 byId
的请求最终将成为对 /api/trpc/post.byId
的请求。
ts
export const appRouter = router({post: router({byId: publicProcedure.input(String).query(async (opts) => {// [...]}),}),});
ts
export const appRouter = router({post: router({byId: publicProcedure.input(String).query(async (opts) => {// [...]}),}),});
批处理
在批处理时,我们将使用数据加载器将同一 HTTP 方法的所有并行过程调用组合到一个请求中。
- 调用的过程名称在
pathname
中用逗号 (,
) 分隔 - 输入参数作为名为
input
的查询参数发送,该参数的形状为Record<number, unknown>
。 - 我们还需要将
batch=1
作为查询参数传递。 - 如果响应具有不同的状态,我们将发送回
207 多状态
(例如,如果一个调用出错而另一个成功)
批处理示例请求
给定一个像这样在 /api/trpc
中公开的路由器:
server/router.tstsx
export const appRouter = t.router({postById: t.procedure.input(String).query(async (opts) => {const post = await opts.ctx.post.findUnique({where: { id: opts.input },});return post;}),relatedPosts: t.procedure.input(String).query(async (opts) => {const posts = await opts.ctx.findRelatedPostsById(opts.input);return posts;}),});
server/router.tstsx
export const appRouter = t.router({postById: t.procedure.input(String).query(async (opts) => {const post = await opts.ctx.post.findUnique({where: { id: opts.input },});return post;}),relatedPosts: t.procedure.input(String).query(async (opts) => {const posts = await opts.ctx.findRelatedPostsById(opts.input);return posts;}),});
... 以及在 React 组件中定义的两个查询:
MyComponent.tsxtsx
export function MyComponent() {const post1 = trpc.postById.useQuery('1');const relatedPosts = trpc.relatedPosts.useQuery('1');return (<pre>{JSON.stringify({post1: post1.data ?? null,relatedPosts: relatedPosts.data ?? null,},null,4,)}</pre>);}
MyComponent.tsxtsx
export function MyComponent() {const post1 = trpc.postById.useQuery('1');const relatedPosts = trpc.relatedPosts.useQuery('1');return (<pre>{JSON.stringify({post1: post1.data ?? null,relatedPosts: relatedPosts.data ?? null,},null,4,)}</pre>);}
以上将导致正好 1 个 HTTP 调用,其数据为:
位置属性 | 值 |
---|---|
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`}),);
批处理示例响应
服务器的示例输出
json
[// result for `postById`{"result": {"data": {"id": "1","title": "Hello tRPC","body": "..."// ...}}},// result for `relatedPosts`{"result": {"data": [/* ... */]}}]
json
[// result for `postById`{"result": {"data": {"id": "1","title": "Hello tRPC","body": "..."// ...}}},// result for `relatedPosts`{"result": {"data": [/* ... */]}}]
HTTP 响应规范
为了拥有一个与传输层无关的规范,我们尝试尽可能地符合 JSON-RPC 2.0。
成功响应
示例 JSON 响应
json
{"result": {"data": {"id": "1","title": "Hello tRPC","body": "..."}}}
json
{"result": {"data": {"id": "1","title": "Hello tRPC","body": "..."}}}
ts
{result: {data: TOutput; // output from procedure}}
ts
{result: {data: TOutput; // output from procedure}}
错误响应
示例 JSON 响应
json
[{"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
[{"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 多状态
(例如,如果一个调用出错而另一个成功) - 有关错误以及如何自定义错误的更多信息,请参阅 错误格式。
错误代码 <-> HTTP 状态
ts
PARSE_ERROR: 400,BAD_REQUEST: 400,UNAUTHORIZED: 401,NOT_FOUND: 404,FORBIDDEN: 403,METHOD_NOT_SUPPORTED: 405,TIMEOUT: 408,CONFLICT: 409,PRECONDITION_FAILED: 412,PAYLOAD_TOO_LARGE: 413,UNPROCESSABLE_CONTENT: 422,TOO_MANY_REQUESTS: 429,CLIENT_CLOSED_REQUEST: 499,INTERNAL_SERVER_ERROR: 500,NOT_IMPLEMENTED: 501,
ts
PARSE_ERROR: 400,BAD_REQUEST: 400,UNAUTHORIZED: 401,NOT_FOUND: 404,FORBIDDEN: 403,METHOD_NOT_SUPPORTED: 405,TIMEOUT: 408,CONFLICT: 409,PRECONDITION_FAILED: 412,PAYLOAD_TOO_LARGE: 413,UNPROCESSABLE_CONTENT: 422,TOO_MANY_REQUESTS: 429,CLIENT_CLOSED_REQUEST: 499,INTERNAL_SERVER_ERROR: 500,NOT_IMPLEMENTED: 501,
错误代码 <-> JSON-RPC 2.0 错误代码
可用代码和 JSON-RPC 代码
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 errorINTERNAL_SERVER_ERROR: -32603,NOT_IMPLEMENTED: -32603,// Implementation specific errorsUNAUTHORIZED: -32001, // 401FORBIDDEN: -32003, // 403NOT_FOUND: -32004, // 404METHOD_NOT_SUPPORTED: -32005, // 405TIMEOUT: -32008, // 408CONFLICT: -32009, // 409PRECONDITION_FAILED: -32012, // 412PAYLOAD_TOO_LARGE: -32013, // 413UNPROCESSABLE_CONTENT: -32022, // 422TOO_MANY_REQUESTS: -32029, // 429CLIENT_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 errorINTERNAL_SERVER_ERROR: -32603,NOT_IMPLEMENTED: -32603,// Implementation specific errorsUNAUTHORIZED: -32001, // 401FORBIDDEN: -32003, // 403NOT_FOUND: -32004, // 404METHOD_NOT_SUPPORTED: -32005, // 405TIMEOUT: -32008, // 408CONFLICT: -32009, // 409PRECONDITION_FAILED: -32012, // 412PAYLOAD_TOO_LARGE: -32013, // 413UNPROCESSABLE_CONTENT: -32022, // 422TOO_MANY_REQUESTS: -32029, // 429CLIENT_CLOSED_REQUEST: -32099, // 499} as const;
覆盖默认 HTTP 方法
要覆盖用于查询/变异的 HTTP 方法,可以使用 methodOverride
选项
server/httpHandler.tstsx
// Your server must separately allow the client to override the HTTP methodconst handler = createHTTPHandler({router: router,allowMethodOverride: true,});
server/httpHandler.tstsx
// Your server must separately allow the client to override the HTTP methodconst handler = createHTTPHandler({router: router,allowMethodOverride: true,});
client/trpc.tstsx
// The client can then specify which HTTP method to use for all queries/mutationsconst client = createTRPCClient<AppRouter>({links: [httpLink({url: `http://localhost:3000`,methodOverride: 'POST', // all queries and mutations will be sent to the tRPC Server as POST requests.}),],});
client/trpc.tstsx
// The client can then specify which HTTP method to use for all queries/mutationsconst client = createTRPCClient<AppRouter>({links: [httpLink({url: `http://localhost:3000`,methodOverride: 'POST', // all queries and mutations will be sent to the tRPC Server as POST requests.}),],});
深入了解
您可以通过深入研究 TypeScript 定义来了解更多详细信息