Definir Routers
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.tstsimport {initTRPC } from '@trpc/server';// You can use any variable name you like.// We use t to keep things simple.constt =initTRPC .create ();export constrouter =t .router ;export constpublicProcedure =t .procedure ;
server/trpc.tstsimport {initTRPC } from '@trpc/server';// You can use any variable name you like.// We use t to keep things simple.constt =initTRPC .create ();export constrouter =t .router ;export constpublicProcedure =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.tstsimport {publicProcedure ,router } from './trpc';constappRouter =router ({greeting :publicProcedure .query (() => 'hello tRPC v10!'),});// Export only the type of a router!// This prevents us from importing server code on the client.export typeAppRouter = typeofappRouter ;
server/_app.tstsimport {publicProcedure ,router } from './trpc';constappRouter =router ({greeting :publicProcedure .query (() => 'hello tRPC v10!'),});// Export only the type of a router!// This prevents us from importing server code on the client.export typeAppRouter = typeofappRouter ;
Uso avanzado
Al inicializar tu router, tRPC te permite:
-
Configurar contextos de solicitud
-
Asignar metadata a los procedures
-
Transformar datos según sea necesario
-
Personalizar la configuración de runtime
Puedes usar method chaining para personalizar tu objeto t durante la inicialización. Por ejemplo:
tsconst t = initTRPC.context<Context>().meta<Meta>().create({/* [...] */});
tsconst t = initTRPC.context<Context>().meta<Meta>().create({/* [...] */});
Configuración de Runtime
tsexport interface RootConfig<TTypes extends RootTypes> {/*** Use a data transformer* @see https://trpc.io/docs/v11/data-transformers*/transformer: TTypes['transformer'];/*** Use custom error formatting* @see https://trpc.io/docs/v11/error-formatting*/errorFormatter: ErrorFormatter<TTypes['ctx'], any>;/*** 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;}
tsexport interface RootConfig<TTypes extends RootTypes> {/*** Use a data transformer* @see https://trpc.io/docs/v11/data-transformers*/transformer: TTypes['transformer'];/*** Use custom error formatting* @see https://trpc.io/docs/v11/error-formatting*/errorFormatter: ErrorFormatter<TTypes['ctx'], any>;/*** 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;}