본문 바로가기
버전: 10.x

라우터 정의하기

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

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 변수의 특정 메서드를 내보내는 것을 확인할 수 있습니다. 이는 코드베이스에서 관용적으로 사용할 절차(procedure)의 일관된 집합을 확립하기 위함입니다.

라우터 정의하기

다음으로 애플리케이션에서 사용할 절차(procedure)가 포함된 라우터를 정의해 보겠습니다. 이제 API "엔드포인트"가 생성되었습니다.

이러한 엔드포인트가 프론트엔드에 노출되려면 어댑터(Adapter)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;

고급 사용법

라우터를 초기화할 때 tRPC를 통해 다음 작업이 가능합니다:

초기화 시 메서드 체이닝을 사용해 t 객체를 커스터마이징할 수 있습니다. 예시:

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

런타임 설정(Runtime Configuration)

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