Расширение возможностей tRPC
Узнайте о продвинутых способах расширения tRPC с помощью пользовательских конструкторов, подключаемых модулей и интеграции с другими библиотеками.
«Расширение возможностей tRPC» — бесплатный урок tRPC End-to-End Type Safe APIs на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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.
Изучай tRPC End-to-End Type Safe APIs с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 10
- Уроки
- 40
Часто задаваемые вопросы
Урок «Расширение возможностей tRPC» бесплатный?
Да — полный текст урока «Расширение возможностей tRPC» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс tRPC End-to-End Type Safe APIs, подпишись на CoddyKit PRO. Курс tRPC End-to-End Type Safe APIs содержит 4 уроков всего.
Чему я научусь в уроке «Расширение возможностей tRPC»?
Узнайте о продвинутых способах расширения tRPC с помощью пользовательских конструкторов, подключаемых модулей и интеграции с другими библиотеками. Ты практикуешь tRPC End-to-End Type Safe APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать tRPC End-to-End Type Safe APIs?
Предыдущий опыт не требуется. tRPC End-to-End Type Safe APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Расширение возможностей tRPC»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке tRPC End-to-End Type Safe APIs?
Да. Каждый урок tRPC End-to-End Type Safe APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Настройка монорепозитория tRPC
- Совместное использование и повторное применение кода
- Расширение возможностей tRPC
- Версионирование и публикация общих пакетов tRPC