การใช้งานกระบวนงานคำค้น
สร้างจุดปลายทางสำหรับดึงข้อมูลแบบอ่านอย่างเดียวด้วยกระบวนงานคำค้นของ tRPC พร้อมชนิดข้อมูลนำเข้าและส่งออก
การใช้งานกระบวนงานคำค้น เป็นบทเรียน 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 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What are tRPC Queries?
Queries are like asking a question to your server. They are designed for fetching data, not changing it. Think of them as the "GET" requests in a traditional REST API.
- Read-only: Queries should never change data on your server.
- Idempotent: Running a query multiple times should produce the same result.
- Cached: Clients can often cache query results for better performance.
They are the foundation for retrieving information in your tRPC application.
Defining a Simple Query
In tRPC, you define queries within a router using .query(). Let's look at the basic structure.
First, you need to initialize tRPC (usually done once in your server setup):
const t = initTRPC.create();Then, define your router and add a query:
import { initTRPC } from '@trpc/server';
// 1. Initialize tRPC
const t = initTRPC.create();
// 2. Create a router
const appRouter = t.router({
// 3. Define a query named 'hello'
hello: t.procedure.query(() => {
return 'Hello from tRPC!';
}),
});
// This snippet shows the core definition.
// A full server setup is needed to run it.Your First Runnable Query (Server)
Let's put it all together into a minimal, runnable tRPC server. This server will host our hello query.
Save this as server.ts and run with ts-node server.ts (after npm install @trpc/server @trpc/server-adapters ts-node typescript).
import { initTRPC } from '@trpc/server';
import { createHTTPServer } from '@trpc/server/adapters/standalone';
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(() => {
console.log('Hello query called on server!');
return 'Hello from tRPC!';
}),
});
export type AppRouter = typeof appRouter;
const server = createHTTPServer({
router: appRouter,
});
server.listen(2025);
console.log('tRPC server listening on http://localhost:2025');Calling a Query from the Client
Now that our server is running, let's call the hello query from a client application. We'll use @trpc/client to create a proxy that mirrors our server's API.
Save this as client.ts. You'll need the server.ts running first.
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
// Simplified AppRouter type for this example
type AppRouter = {
hello: {
_def: {
_input_in: undefined;
_input_out: undefined;
_output_in: string;
_output_out: string;
};
};
};
const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:2025',
}),
],
});
async function callHello() {
try {
const greeting = await trpc.hello.query();
console.log(greeting); // Expected: Hello from tRPC!
} catch (error) {
console.error('Error calling hello query:', error);
}
}
callHello();Passing Data to Queries
Often, you need to send data to your queries, for example, to fetch a specific user by ID. tRPC handles this beautifully with input schemas.
You define the expected input using a validation library like Zod. This ensures your input is always type-safe and valid, both on the client and server.
- Use
.input()aftert.procedure. - Provide a Zod schema to define the shape of your input.
- The input will be available in the
inputproperty of theresolvefunction's arguments.
Querying with an ID (Server)
Let's modify our server to fetch a "user" by their ID. We'll use Zod to validate that the input is a number.
Update your server.ts with this new procedure:
import { initTRPC } from '@trpc/server';
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { z } from 'zod'; // Import Zod
const t = initTRPC.create();
const appRouter = t.router({
getUserById: t.procedure
.input(z.object({ id: z.number() })) // Define input schema
.query(({ input }) => { // Access input here
console.log(`Fetching user with ID: ${input.id}`);
// In a real app, you'd fetch from a database
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
return users.find(user => user.id === input.id) || null;
}),
});
export type AppRouter = typeof appRouter;
const server = createHTTPServer({
router: appRouter,
});
server.listen(2025);
console.log('tRPC server listening on http://localhost:2025');Calling Query with Input (Client)
Now, from the client, we can call our getUserById query and pass the required id. tRPC will ensure the input matches the Zod schema defined on the server, giving you type safety from end-to-end.
Update your client.ts to call this new query:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
// Simplified AppRouter for example
type AppRouter = {
getUserById: {
_def: {
_input_in: { id: number };
_input_out: { id: number };
_output_in: { id: number; name: string } | null;
_output_out: { id: number; name: string } | null;
};
};
};
const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:2025',
}),
],
});
async function callGetUser() {
try {
const user1 = await trpc.getUserById.query({ id: 1 });
console.log('User 1:', user1); // Expected: User 1: { id: 1, name: 'Alice' }
const user3 = await trpc.getUserById.query({ id: 3 });
console.log('User 3:', user3); // Expected: User 3: null
} catch (error) {
console.error('Error calling getUserById query:', error);
}
}
callGetUser();Type Safety in Query Outputs
One of tRPC's biggest advantages is its end-to-end type safety. When you define a query, tRPC automatically infers the output type based on what your resolve function returns.
- No need to manually define response interfaces.
- If your server's return type changes, your client code will automatically show a TypeScript error.
- This catches bugs early, before runtime!
For our getUserById query, tRPC correctly infers the return type as { id: number; name: string } | null.
Query Best Practices
As you build more queries, keep these tips in mind:
- Keep it Read-Only: Never perform side effects (like database writes) in a query.
- Clear Naming: Name your queries descriptively (e.g.,
getUserById,listPosts). - Granular Inputs: Use specific Zod schemas for inputs to ensure strict validation.
- Error Handling: While tRPC propagates errors, consider specific error types for better client feedback (more on this in a later lesson!).
Queries are fundamental for fetching data. Next, we'll look at Mutations for changing data.
Query Procedure Check
You've learned how to define and use tRPC query procedures. Let's test your understanding.
Recap: Query Procedures
Great job! In this lesson, you learned about tRPC Query procedures.
- Queries are for fetching read-only data from your server.
- You define them using
t.procedure.query(...)within your router. - You can add input validation using
.input(z.object(...))with Zod. - tRPC provides end-to-end type safety by inferring output types automatically.
You now have the tools to build powerful, type-safe data fetching endpoints! Next, we'll explore Mutations for data manipulation.
คำถามที่พบบ่อย
บทเรียน “การใช้งานกระบวนงานคำค้น” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การใช้งานกระบวนงานคำค้น” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การใช้งานกระบวนงานคำค้น”
สร้างจุดปลายทางสำหรับดึงข้อมูลแบบอ่านอย่างเดียวด้วยกระบวนงานคำค้นของ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การใช้งานกระบวนงานคำค้น” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม
ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การจัดโครงสร้างด้วยเราเตอร์ tRPC
- การใช้งานกระบวนงานคำค้น
- การพัฒนากระบวนงานการกลายข้อมูล
- การรวมและการซ้อนเราเตอร์