Saltar al contenido principal
Versión: 11.x

Definir Routers

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Para comenzar a construir tu API basada en tRPC, primero deberás definir tu router. Una vez domines los fundamentos, podrás personalizar tus routers para casos de uso más avanzados.

Inicializar tRPC

Debes inicializar tRPC exactamente una vez por aplicación. Múltiples instancias de tRPC causarán problemas.

server/trpc.ts
ts
import { initTRPC } from '@trpc/server';
 
// You can use any variable name you like.
// We use t to keep things simple.
const t = initTRPC.create();
 
export const router = t.router;
export const publicProcedure = t.procedure;
server/trpc.ts
ts
import { initTRPC } from '@trpc/server';
 
// You can use any variable name you like.
// We use t to keep things simple.
const t = initTRPC.create();
 
export const router = t.router;
export const publicProcedure = t.procedure;

Notarás que exportamos ciertos métodos de la variable t en lugar de t misma. Esto es para establecer un conjunto de procedimientos que usaremos idiomáticamente en nuestra base de código.

Definir un router

A continuación, definamos un router con un procedure para usar en nuestra aplicación. Acabamos de crear un "endpoint" de API.

Para que estos endpoints sean accesibles desde el frontend, tu Adapter debe configurarse con tu instancia de appRouter.

server/_app.ts
ts
import { publicProcedure, router } from './trpc';
 
const appRouter = router({
greeting: publicProcedure.query(() => 'hello tRPC v11!'),
});
 
// Export only the type of a router!
// This prevents us from importing server code on the client.
export type AppRouter = typeof appRouter;
server/_app.ts
ts
import { publicProcedure, router } from './trpc';
 
const appRouter = router({
greeting: publicProcedure.query(() => 'hello tRPC v11!'),
});
 
// Export only the type of a router!
// This prevents us from importing server code on the client.
export type AppRouter = typeof appRouter;

Definir un sub-router en línea

Al definir un sub-router en línea, puedes representar tu router como un objeto simple.

En el siguiente ejemplo, nested1 y nested2 son equivalentes:

server/_app.ts
ts
import * as trpc from '@trpc/server';
import { publicProcedure, router } from './trpc';
 
const appRouter = router({
// Using the router() method
nested1: router({
proc: publicProcedure.query(() => '...'),
}),
// Using an inline sub-router
nested2: {
proc: publicProcedure.query(() => '...'),
},
});
server/_app.ts
ts
import * as trpc from '@trpc/server';
import { publicProcedure, router } from './trpc';
 
const appRouter = router({
// Using the router() method
nested1: router({
proc: publicProcedure.query(() => '...'),
}),
// Using an inline sub-router
nested2: {
proc: publicProcedure.query(() => '...'),
},
});

Uso avanzado

Al inicializar tu router, tRPC te permite:

Puedes usar method chaining para personalizar tu objeto t durante la inicialización. Por ejemplo:

ts
const t = initTRPC.context<Context>().meta<Meta>().create({
/* [...] */
});
ts
const t = initTRPC.context<Context>().meta<Meta>().create({
/* [...] */
});

Configuración de Runtime

ts
interface RootConfig {
/**
* Use a data transformer
* @see https://trpc.io/docs/v11/data-transformers
*/
transformer: DataTransformerOptions;
 
/**
* Use custom error formatting
* @see https://trpc.io/docs/v11/error-formatting
*/
errorFormatter: ErrorFormatter;
 
/**
* Allow `@trpc/server` to run in non-server environments
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default false
*/
allowOutsideOfServer: boolean;
 
/**
* Is this a server environment?
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'
*/
isServer: boolean;
 
/**
* Is this development?
* Will be used to decide if the API should return stack traces
* @default process.env.NODE_ENV !== 'production'
*/
isDev: boolean;
}
ts
interface RootConfig {
/**
* Use a data transformer
* @see https://trpc.io/docs/v11/data-transformers
*/
transformer: DataTransformerOptions;
 
/**
* Use custom error formatting
* @see https://trpc.io/docs/v11/error-formatting
*/
errorFormatter: ErrorFormatter;
 
/**
* Allow `@trpc/server` to run in non-server environments
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default false
*/
allowOutsideOfServer: boolean;
 
/**
* Is this a server environment?
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'
*/
isServer: boolean;
 
/**
* Is this development?
* Will be used to decide if the API should return stack traces
* @default process.env.NODE_ENV !== 'production'
*/
isDev: boolean;
}