0Pricing
tRPC End-to-End Type Safe APIs · บทเรียน

การแบ่งปันโค้ดและการนำกลับมาใช้ใหม่

เรียนรู้กลยุทธ์เพื่อเพิ่มการใช้โค้ดร่วมกันระหว่างไคลเอนต์และเซิร์ฟเวอร์ โดยเฉพาะชนิดข้อมูลและเครื่องมืออรรถประโยชน์

การแบ่งปันโค้ดและการนำกลับมาใช้ใหม่ เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน tRPC End-to-End Type Safe APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Share Code?

In a tRPC monorepo, you often have multiple applications (client, server, admin panel) that need to interact with the same data structures or perform similar tasks.

Code sharing is a powerful technique that helps reduce duplication, ensure consistency, and improve the overall maintainability of your project.

Types Across Client & Server

One of tRPC's biggest advantages is end-to-end type safety. This means your frontend automatically knows the types of data your backend sends and receives.

This magic relies heavily on sharing TypeScript types and interfaces between your client and server applications.

Defining a Shared Type

Let's create a simple User interface in a dedicated packages/types directory. This package will be imported by both your server and client.

/* packages/types/src/user.ts */
export interface User {
  id: string;
  name: string;
  email: string;
}

Server-side Shared Types

Now, we can use this User type to define the expected output of a tRPC query on our backend. This ensures the data sent from the server strictly adheres to the User structure.

/* packages/server/src/router/user.ts */
import { publicProcedure, router } from '../trpc';
import { User } from '@my-monorepo/types'; // Import shared type

export const userRouter = router({
  getUsers: publicProcedure
    .query(async () => {
      const users: User[] = [
        { id: '1', name: 'Alice', email: 'alice@example.com' },
        { id: '2', name: 'Bob', email: 'bob@example.com' },
      ];
      return users; // tRPC infers return type as User[]
    }),
});

Client-side Shared Types

On the client, tRPC automatically infers the types for users based on the server's definition. While explicit import isn't always needed for inference, it improves clarity and allows you to use the type for local client-side state or props.

/* packages/client/src/components/UserList.tsx */
import { trpc } from '../utils/trpc';
import { User } from '@my-monorepo/types'; // Optional, but good practice

function UserList() {
  const { data: users, isLoading } = trpc.user.getUsers.useQuery();

  if (isLoading) return <div>Loading users...</div>;

  return (
    <div>
      {users?.map((user: User) => ( // 'user' is typed as User
        <p key={user.id}>{user.name} ({user.email})</p>
      ))}
    </div>
  );
}

Sharing Utility Functions

Beyond types, many other pieces of code can be shared. This includes common utility functions, constants, validation schemas (like Zod schemas), or even shared UI components if you're using a component library.

Sharing these helps maintain a consistent user experience and reduces redundant code across your applications.

Creating a Utility Package

Let's create a simple utility function in a packages/utils directory that formats a full name. We'll also include a shared constant.

/* packages/utils/src/format.ts */
export function formatFullName(firstName: string, lastName: string): string {
  return `${firstName} ${lastName}`;
}

export const APP_NAME = 'CoddyKit Learn'; // Example constant

Server-side Utilities

You can import and use these shared utility functions directly in your tRPC backend procedures. This ensures consistent logic, regardless of whether it's triggered by an API call or internal server processes.

/* packages/server/src/router/profile.ts */
import { publicProcedure, router } from '../trpc';
import { formatFullName } from '@my-monorepo/utils'; // Import shared utility
import { z } from 'zod'; // Assuming Zod is configured

export const profileRouter = router({
  getUserProfile: publicProcedure
    .input(z.object({ firstName: z.string(), lastName: z.string() }))
    .query(({ input }) => {
      const fullName = formatFullName(input.firstName, input.lastName);
      return { greeting: `Hello, ${fullName}!` };
    }),
});

Client-side Utilities

Similarly, your client-side application can import and use the exact same utility functions and constants. This guarantees that calculations or displayed text are consistent with the server's logic.

/* packages/client/src/components/Greeting.tsx */
import { formatFullName, APP_NAME } from '@my-monorepo/utils'; // Import shared utility

function Greeting() {
  const firstName = "Jane";
  const lastName = "Doe";
  const formattedName = formatFullName(firstName, lastName);

  return (
    <div>
      <h1>Welcome to {APP_NAME}!</h1>
      <p>User: {formattedName}</p>
    </div>
  );
}

Best Practices for Shared Code

  • Granularity: Create small, focused shared packages (e.g., types, utils, ui).
  • Dependencies: Shared packages should have minimal external dependencies to avoid bloating other apps.
  • Avoid Circular Deps: Be careful not to create circular dependencies between shared packages or between app and shared packages.
  • Testing: Test shared code thoroughly, as changes can affect multiple applications.

Shared Code Benefits

Which of the following are primary benefits of sharing types and utility functions between client and server in a tRPC monorepo?

Recap: Sharing is Caring!

We explored how sharing types and utility functions in a tRPC monorepo is key to maximizing efficiency. This approach reduces duplication, enhances type safety, and improves overall maintainability across your client and server applications. By structuring your project carefully, you can build robust and consistent full-stack applications.

คำถามที่พบบ่อย

บทเรียน “การแบ่งปันโค้ดและการนำกลับมาใช้ใหม่” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การแบ่งปันโค้ดและการนำกลับมาใช้ใหม่” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การแบ่งปันโค้ดและการนำกลับมาใช้ใหม่”

เรียนรู้กลยุทธ์เพื่อเพิ่มการใช้โค้ดร่วมกันระหว่างไคลเอนต์และเซิร์ฟเวอร์ โดยเฉพาะชนิดข้อมูลและเครื่องมืออรรถประโยชน์ คุณปฏิบัติ tRPC End-to-End Type Safe APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การแบ่งปันโค้ดและการนำกลับมาใช้ใหม่” ใช้เวลานานแค่ไหน

บทเรียน 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