본문으로 건너뛰기
버전: 11.x

라우터 정의

tRPC 기반 API 구축을 시작하려면 먼저 라우터를 정의해야 합니다. 기본 개념을 숙달한 후에는 더 고급 사용 사례에 맞게 라우터 커스터마이징을 수행할 수 있습니다.

tRPC 초기화

tRPC는 애플리케이션당 정확히 한 번만 초기화해야 합니다. tRPC 인스턴스가 여러 개 존재하면 문제가 발생할 수 있습니다.

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;

여기서는 t 자체 대신 t 변수의 특정 메서드를 내보내고 있음을 알 수 있습니다. 이는 코드베이스에서 관용적으로 사용할 프로시저 집합을 확립하기 위한 것입니다.

라우터 정의

다음으로 애플리케이션에서 사용할 프로시저를 포함하는 라우터를 정의합니다. 이렇게 하면 API "엔드포인트"가 생성됩니다.

이 엔드포인트를 프론트엔드에 노출하려면 어댑터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;

인라인 서브라우터 정의

인라인 서브 라우터를 정의하면 라우터를 일반 객체로 표현할 수 있습니다.

아래 예시에서 nested1nested2는 동일합니다:

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

고급 사용법

라우터를 초기화할 때 tRPC는 다음을 허용합니다:

메서드 체이닝을 사용하여 초기화 시 t 객체를 사용자 정의할 수 있습니다. 예를 들어:

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

런타임 구성

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