跳至主内容
版本:10.x

核心概念

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

什么是 RPC?应如何理解其设计理念?

本质是函数调用

RPC 是"远程过程调用(Remote Procedure Call)"的缩写。它允许在一台计算机(客户端)上调用另一台计算机(服务器)上的函数。与传统 HTTP/REST API 通过 URL 调用获取响应不同,RPC 通过直接调用函数获取结果。

ts
// HTTP/REST
const res = await fetch('/api/users/1');
const user = await res.json();
// RPC
const user = await api.users.getById({ id: 1 });
ts
// HTTP/REST
const res = await fetch('/api/users/1');
const user = await res.json();
// RPC
const user = await api.users.getById({ id: 1 });

tRPC(TypeScript 远程过程调用)是专为 TypeScript 单体仓库设计的 RPC 实现方案。它在保留 RPC 核心特性的同时,具有独特的实现风格。

无需考虑 HTTP/REST 的实现细节

观察 tRPC 应用的网络流量时,你会看到标准的 HTTP 请求/响应,但在编写应用代码时无需关注这些底层细节。你只需调用函数,tRPC 会处理其余工作。应当忽略 HTTP 动词等实现细节——这些在 REST API 中承载语义的元素,在 RPC 中会融入函数命名,例如使用 getUser(id) 而非 GET /users/:id

术语表

以下是 tRPC 生态系统中常用的核心术语。这些术语将贯穿整个文档,建议提前熟悉。大部分概念在文档中都有专门的说明页面。

TermDescription
Procedure ↗API endpoint - can be a query, mutation, or subscription.
QueryA procedure that gets some data.
MutationA procedure that creates, updates, or deletes some data.
Subscription ↗A procedure that creates a persistent connection and listens to changes.
Router ↗A collection of procedures (and/or other routers) under a shared namespace.
Context ↗Stuff that every procedure can access. Commonly used for things like session state and database connections.
Middleware ↗A function that can run code before and after a procedure. Can modify context.
Validation ↗"Does this input data contain the right stuff?"