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

경로 메타데이터

비공식 베타 번역

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

경로 메타데이터를 사용하면 선택적인 경로별 meta 속성을 추가할 수 있으며, 이 속성은 모든 middleware 함수 매개변수에서 사용 가능합니다.

타입이 지정된 메타데이터로 라우터 생성

jsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean
}
export const appRouter = trpc.router<Context, Meta>();
jsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean
}
export const appRouter = trpc.router<Context, Meta>();

경로별 인증 설정 예시

server.ts
tsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean;
}
export const appRouter = trpc
.router<Context, Meta>()
.middleware(async ({ meta, next, ctx }) => {
// only check authorization if enabled
if (meta?.hasAuth && !ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('hello', {
meta: {
hasAuth: false,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
})
.query('protected-hello', {
meta: {
hasAuth: true,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
});
server.ts
tsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean;
}
export const appRouter = trpc
.router<Context, Meta>()
.middleware(async ({ meta, next, ctx }) => {
// only check authorization if enabled
if (meta?.hasAuth && !ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next();
})
.query('hello', {
meta: {
hasAuth: false,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
})
.query('protected-hello', {
meta: {
hasAuth: true,
},
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
});