Especificación HTTP RPC
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Métodos <-> Mapeo de tipos
| HTTP Method | Mapping | Notes |
|---|---|---|
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 |
Procesamiento por lotes
En el procesamiento por lotes, combinamos todas las llamadas a procedimientos paralelos del mismo tipo en una sola solicitud usando un data loader.
-
Los nombres de los procedimientos llamados se combinan con una coma (
,) en elpathname -
Los parámetros de entrada se envían como un parámetro de consulta llamado
inputque tiene la formaRecord<number, unknown>. -
También necesitamos pasar
batch=1como parámetro de consulta. -
Si la respuesta contiene diferentes estados, devolvemos
207 Multi-Status(ej. si una llamada falló y otra tuvo éxito)
Ejemplo de solicitud por lotes
Dado un enrutador como este expuesto en /api/trpc:
server/router.tstsxexport 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.tstsxexport 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;},});
.. Y dos consultas definidas así en un componente de React:
MyComponent.tsxtsxexport 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.tsxtsxexport 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>);}
Lo anterior resultaría en exactamente 1 llamada HTTP con estos datos:
| Location property | Value |
|---|---|
pathname | /api/trpc/postById,relatedPosts |
search | ?batch=1&input=%7B%220%22%3A%221%22%2C%221%22%3A%221%22%7D * |
*) El input en lo anterior es el resultado de:
tsencodeURIComponent(JSON.stringify({0: '1', // <-- input for `postById`1: '1', // <-- input for `relatedPosts`}),);
tsencodeURIComponent(JSON.stringify({0: '1', // <-- input for `postById`1: '1', // <-- input for `relatedPosts`}),);
Ejemplo de respuesta por lotes
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": [/* ... */]}}]
Especificación de respuesta HTTP
Para tener una especificación que funcione independientemente de la capa de transporte, intentamos ajustarnos a JSON-RPC 2.0 siempre que sea posible.
Respuesta exitosa
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}}
Respuesta de error
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"}}}}]
-
Cuando es posible, propagamos los códigos de estado HTTP del error lanzado.
-
Si la respuesta contiene diferentes estados, devolvemos
207 Multi-Status(ej. si una llamada falló y otra tuvo éxito) -
Para más información sobre errores y cómo personalizarlos, consulta Formato de errores.
Códigos de error <-> Estado HTTP
tsPARSE_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,
tsPARSE_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,
Códigos de error <-> Códigos de error 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 errorsUNAUTHORIZED: -32001, // 401FORBIDDEN: -32003, // 403NOT_FOUND: -32004, // 404METHOD_NOT_SUPPORTED: -32005, // 405TIMEOUT: -32008, // 408CONFLICT: -32009, // 409PRECONDITION_FAILED: -32012, // 412PAYLOAD_TOO_LARGE: -32013, // 413CLIENT_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 errorsUNAUTHORIZED: -32001, // 401FORBIDDEN: -32003, // 403NOT_FOUND: -32004, // 404METHOD_NOT_SUPPORTED: -32005, // 405TIMEOUT: -32008, // 408CONFLICT: -32009, // 409PRECONDITION_FAILED: -32012, // 412PAYLOAD_TOO_LARGE: -32013, // 413CLIENT_CLOSED_REQUEST: -32099, // 499} as const;
Profundizar
Puedes leer más detalles examinando las definiciones de TypeScript en: