Aller au contenu principal
Version : 10.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 v10!'),
});
 
// 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 v10!'),
});
 
// Export only the type of a router!
// This prevents us from importing server code on the client.
export type AppRouter = typeof appRouter;

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
export interface RuntimeConfig<TTypes extends RootConfigTypes> {
/**
* Use a data transformer
* @see https://trpc.io/docs/data-transformers
*/
transformer: TTypes['transformer'];
/**
* Use custom error formatting
* @see https://trpc.io/docs/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;
}
ts
export interface RuntimeConfig<TTypes extends RootConfigTypes> {
/**
* Use a data transformer
* @see https://trpc.io/docs/data-transformers
*/
transformer: TTypes['transformer'];
/**
* Use custom error formatting
* @see https://trpc.io/docs/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;
}