tRPC End-to-End Type Safe APIs · 강의

tRPC 기능 확장

사용자 지정 빌더와 플러그인, 다른 라이브러리와의 연동을 통해 tRPC를 확장하는 고급 방법을 알아봅니다.

레슨 3/411개 단계

tRPC 기능 확장은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Extend tRPC's Core

tRPC is incredibly powerful out-of-the-box, but sometimes your application needs more custom control and specialized behavior. This lesson will show you how to extend tRPC beyond basic middleware.

We'll explore custom procedure builders for creating specialized API endpoints and discuss how to integrate tRPC seamlessly with other libraries like ORMs.

Why Custom Builders?

Standard middleware is great for applying common logic to all or a group of procedures, such as authentication or logging.

But what if you need to define specific types of procedures, like adminProcedure or publicProcedure, each with unique context properties or pre-configured middleware chains? Custom procedure builders are perfect for this!

Crafting a Builder with `createBuilder`

tRPC provides the createBuilder utility to help you define your own procedure factory. This builder can extend the context (ctx), add metadata, or apply middleware automatically to any procedure built with it.

It allows you to abstract common setup logic into a reusable pattern, making your API definitions cleaner and more consistent.

Builder Example: Admin Procedure

Let's create an adminProcedure. This builder ensures the user is not only logged in (via protectedProcedure) but also has an isAdmin flag set in their context. This logic is then automatically applied to any procedure using adminProcedure.

// Minimal tRPC-like setup for demonstration
type Context = { user?: { id: number; isAdmin?: boolean } };

const mockProcedure = {
  use: (middleware: any) => ({
    use: (nextMiddleware: any) => ({
      _isBuilder: true,
      _middlewares: [middleware, nextMiddleware]
    }),
    _isBuilder: true,
    _middlewares: [middleware]
  }),
  _isBuilder: true,
  _middlewares: []
};

const t = {
  procedure: mockProcedure
};

// --- Actual tRPC Builder Code ---
const protectedProcedure = t.procedure.use(async ({ ctx, next }: any) => {
  if (!ctx.user) {
    throw new Error('Not authenticated');
  }
  return next({ ctx: { ...ctx, user: ctx.user } });
});

const adminProcedure = protectedProcedure.use(async ({ ctx, next }: any) => {
  if (!ctx.user?.isAdmin) {
    throw new Error('Not an admin!');
  }
  return next({ ctx: { ...ctx, user: ctx.user } });
});

console.log("Protected procedure builder defined.");
console.log("Admin procedure builder defined.");
console.log("Admin procedure has " + adminProcedure._middlewares.length + " middlewares.");

Benefits of Custom Builders

Custom builders offer several significant advantages:

  • Reusability: Define complex logic once and apply it across many procedures.
  • Type Safety: Enforce specific context types for groups of procedures.
  • Readability: Procedures become self-documenting (e.g., adminProcedure.query(...) clearly indicates its requirements).
  • Consistency: Ensure all procedures of a certain type adhere to specific rules and checks.

Integration with External Libraries

tRPC is unopinionated about your data layer. This means you can easily integrate it with any ORM (like Prisma, Drizzle), database client, or external API service you prefer.

The key to this seamless integration is often to initialize instances of these clients and attach them to your tRPC context. This makes them readily available to all your procedures.

Contextualizing an ORM (Prisma)

A very common pattern in tRPC applications is to initialize your ORM client (e.g., Prisma Client) and then attach that instance to your tRPC context object.

This allows all your tRPC procedures to access the database client via ctx.prisma, centralizing its management and providing type safety.

// Minimal tRPC-like setup for demonstration
type MockPrismaClient = {
  user: {
    findUnique: (args: { where: { id: number } }) => { id: number; name: string } | null;
  };
};

type ContextWithPrisma = {
  prisma: MockPrismaClient;
};

const mockProcedure = {
  query: (handler: (opts: { ctx: ContextWithPrisma }) => any) => ({
    _handler: handler,
    _isQuery: true
  })
};

const t = {
  procedure: mockProcedure
};

// --- Actual tRPC Context Integration ---
const publicProcedure = t.procedure;

const getUserProcedure = publicProcedure.query(async ({ ctx }) => {
  const user = await ctx.prisma.user.findUnique({ where: { id: 1 } });
  return user ? `User name: ${user.name}` : 'User not found.';
});

// --- Demonstration (conceptual execution) ---
const mockPrisma: MockPrismaClient = {
  user: {
    findUnique: (args) => {
      if (args.where.id === 1) {
        return { id: 1, name: 'Alice' };
      }
      return null;
    }
  }
};

const mockContext: ContextWithPrisma = { prisma: mockPrisma };

console.log("Prisma client attached to context type.");
console.log("Conceptual handler output for user 1:");
console.log(await getUserProcedure._handler({ ctx: mockContext }));

The Power of Plugins (Conceptual)

Beyond builders, tRPC offers an experimental createTRPCPlugin API. Plugins provide even deeper hooks into tRPC's internals, allowing you to customize error formatting, add custom data transformers, or modify the request lifecycle in advanced ways.

They are designed for truly complex, core-level extensions that affect how tRPC operates at a foundational level.

When to Use What?

Choosing between custom builders and plugins depends on your extension needs:

  • Custom Builders: Best for defining specific types of procedures, enriching the context object, or applying common middleware chains. They operate at the procedure definition level.
  • Plugins: Ideal for modifying tRPC's core behavior, such as custom error handling, data serialization/deserialization, or integrating with external systems at a global, foundational level.

Quick Check

Which of the following are key benefits of using custom tRPC procedure builders?

Summary of Extensions

In this lesson, we explored how to extend tRPC's capabilities. We learned to use custom procedure builders to create specialized, reusable procedures like adminProcedure, enhancing reusability, type safety, and consistency.

We also saw how to integrate external libraries like ORMs by attaching them to the tRPC context. Finally, we touched upon the advanced potential of tRPC plugins for deeper core modifications. These tools empower you to tailor tRPC to your application's unique needs.

무료로 시작

AI 튜터와 함께 tRPC End-to-End Type Safe APIs을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
10
레슨
40

자주 묻는 질문

“tRPC 기능 확장” 강의는 무료인가요?

네 — “tRPC 기능 확장” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“tRPC 기능 확장”에서 뭘 배우나요?

사용자 지정 빌더와 플러그인, 다른 라이브러리와의 연동을 통해 tRPC를 확장하는 고급 방법을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“tRPC 기능 확장” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. tRPC 모노레포 설정
  2. 코드 공유와 재사용성
  3. tRPC 기능 확장
  4. 공유 tRPC 패키지의 버전 관리와 게시
← tRPC End-to-End Type Safe APIs(으)로 돌아가기