การผสานรวม Zod ในกระบวนงาน tRPC
นำสคีมา Zod ไปใช้โดยตรงกับข้อมูลนำเข้าของคำค้นและการกลายข้อมูลใน tRPC เพื่อการตรวจสอบอัตโนมัติ
การผสานรวม Zod ในกระบวนงาน tRPC เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน tRPC End-to-End Type Safe APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Zod for tRPC Inputs
Welcome! In this lesson, we'll learn how to integrate Zod schemas directly into your tRPC procedures. This powerful combination ensures your API inputs are always valid and type-safe from end-to-end.
You'll see how to apply Zod for both query and mutation procedures, making your backend more robust and developer-friendly.
Why Validate Inputs?
Input validation is a critical part of building secure and reliable APIs. It's like a quality check at the entrance of your backend.
- Security: Prevents malicious or malformed data from reaching your server logic.
- Data Integrity: Ensures your database only stores valid and expected data formats.
- Predictability: Your backend logic can trust the shape of incoming data, reducing runtime errors.
- Better DX: Developers get immediate feedback on incorrect inputs.
The `.input()` Method
tRPC makes integrating Zod incredibly simple. Each tRPC procedure (query, mutation, or subscription) has an .input() method.
This method accepts a Zod schema, which tRPC then uses to automatically validate any incoming data for that procedure. If the input doesn't match the schema, tRPC handles the error for you!
Query Input Validation
For queries, you often expect parameters like an ID or a search term. Zod helps ensure these inputs are of the correct type and format.
Let's look at an example where we want to fetch a user by their unique ID. We'll use Zod to ensure the userId is a valid UUID string.
Query Procedure Example
Here's how you define a tRPC query procedure that uses a Zod schema to validate its input:
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
// Minimal tRPC context setup
const t = initTRPC.create();
// Define a query procedure with Zod input validation
const getUserById = t.procedure
.input(z.object({
userId: z.string().uuid("Invalid user ID format"),
}))
.query(({ input }) => {
// In a real app, this would fetch from a database
console.log(`Fetching user: ${input.userId}`);
return { id: input.userId, name: "Alice" }; // Mock data
});
// To use this, you'd add it to a tRPC router, e.g.:
// export const appRouter = t.router({ getUserById });Mutation Input Validation
Mutations often involve creating or updating data, which means they typically accept more complex input objects. Zod is perfect for validating these structures.
Consider a scenario where you want to create a new blog post. We'll validate its title and optional content to ensure they meet certain criteria.
Mutation Procedure Example
Here's a mutation procedure that validates input for creating a new post using a Zod object schema:
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
// Minimal tRPC context setup
const t = initTRPC.create();
// Define a mutation procedure with Zod input validation
const createPost = t.procedure
.input(z.object({
title: z.string().min(5, "Title must be at least 5 characters"),
content: z.string().optional(),
authorId: z.string().uuid("Invalid author ID"),
}))
.mutation(({ input }) => {
// This would typically save data to a database
console.log(`Creating post: "${input.title}" by ${input.authorId}`);
return { id: "new-post-uuid", ...input, createdAt: new Date() }; // Mock
});
// To use this, you'd add it to a tRPC router, e.g.:
// export const appRouter = t.router({ createPost });Automatic Validation Errors
One of the biggest advantages of integrating Zod directly with tRPC is automatic error handling.
- If a client sends input that doesn't match your Zod schema, tRPC will automatically catch the validation error.
- It then sends a standardized
BAD_REQUESTerror response to the client, including details about why the validation failed. - This means you don't need to write manual
try/catchblocks for basic input validation!
Benefits of Direct Integration
Combining Zod with tRPC's .input() method provides several powerful benefits:
- End-to-End Type Safety: Your Zod schema defines the exact input type, which tRPC automatically infers and shares with your client.
- Single Source of Truth: Define validation rules once, and they apply on both the server (runtime) and client (compile-time).
- Reduced Boilerplate: No need for manual validation checks or separate DTOs (Data Transfer Objects).
- Clear API Contracts: Your procedures clearly state their input requirements through their Zod schemas.
Quick Check: Zod in tRPC
You've learned how Zod schemas are integrated into tRPC procedures. Let's test your understanding!
Recap: Zod & tRPC Synergy
Great job! You've successfully learned how to integrate Zod schemas into your tRPC procedures.
- We saw that the
.input()method is key for applying Zod schemas to both queries and mutations. - This integration provides automatic validation, end-to-end type safety, and clear API contracts.
- By leveraging Zod within tRPC, you build more robust, secure, and developer-friendly APIs with less effort.
Next up, we'll explore more advanced Zod schemas!
เรียนรู้ tRPC End-to-End Type Safe APIs ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 10
- บทเรียน
- 40
คำถามที่พบบ่อย
บทเรียน “การผสานรวม Zod ในกระบวนงาน tRPC” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การผสานรวม Zod ในกระบวนงาน tRPC” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวม Zod ในกระบวนงาน tRPC”
นำสคีมา Zod ไปใช้โดยตรงกับข้อมูลนำเข้าของคำค้นและการกลายข้อมูลใน tRPC เพื่อการตรวจสอบอัตโนมัติ คุณปฏิบัติ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การผสานรวม Zod ในกระบวนงาน tRPC” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม
ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รู้จักสคีมา Zod
- การกำหนดสคีมา Zod ที่ซับซ้อน
- การผสานรวม Zod ในกระบวนงาน tRPC
- การแปลงและปรับแต่งข้อมูล Zod