Aller au contenu principal
Version : 11.x

Définir des routeurs

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Pour commencer à construire votre API basée sur tRPC, vous devez d'abord définir votre routeur. Une fois les bases maîtrisées, vous pouvez personnaliser vos routeurs pour des cas d'utilisation plus avancés.

Initialiser tRPC

Vous devez initialiser tRPC exactement une fois par application. Plusieurs instances de tRPC causeront des problèmes.

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;

Vous remarquerez que nous exportons certaines méthodes de la variable t plutôt que t elle-même. Cela permet d'établir un ensemble de procédures que nous utiliserons de manière idiomatique dans notre codebase.

Définition d'un routeur

Définissons ensuite un routeur avec une procédure à utiliser dans notre application. Nous venons de créer un "endpoint" API.

Pour que ces endpoints soient exposés au frontend, votre Adaptateur doit être configuré avec votre instance 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;

Définition d'un sous-routeur en ligne

Lorsque vous définissez un sous-routeur en ligne, vous pouvez représenter votre routeur comme un objet simple.

Dans l'exemple ci-dessous, nested1 et nested2 sont équivalents :

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(() => '...'),
},
});

Utilisation avancée

Lors de l'initialisation de votre routeur, tRPC vous permet de :

Vous pouvez utiliser le chaînage de méthodes pour personnaliser votre objet t lors de l'initialisation. Par exemple :

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

Configuration d'exécution

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;
}