Skip to main content
Version: 10.x

概念

什么是 RPC?我应该采取什么心态?

¥What is RPC? What mindset should I adopt?

这只是功能

¥It's just functions

RPC 是 "远程过程调用" 的缩写。它是一种从另一台计算机(客户端)调用一台计算机(服务器)上的函数的方法。使用传统的 HTTP/REST API,你可以调用 URL 并获得响应。使用 RPC,你可以调用函数并获得响应。

¥RPC is short for "Remote Procedure Call". It is a way of calling functions on one computer (the server) from another computer (the client). With traditional HTTP/REST APIs, you call a URL and get a response. With RPC, you call a function and get a response.

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 远程过程调用)是 RPC 的一种实现,专为 TypeScript monorepos 设计。它有自己的风格,但其核心是 RPC。

¥tRPC (TypeScript Remote Procedure Call) is one implementation of RPC, designed for TypeScript monorepos. It has its own flavor, but is RPC at its heart.

不用考虑 HTTP/REST 实现细节

¥Don't think about HTTP/REST implementation details

如果你检查 tRPC 应用的网络流量,你会发现它是相当标准的 HTTP 请求和响应,但你在编写应用代码时无需考虑实现细节。你调用函数,tRPC 会处理其他所有事情。你应该忽略 HTTP 动词之类的细节,因为它们在 REST API 中具有含义,但在 RPC 中却是函数名称的一部分,例如:getUser(id) 而不是 GET /users/:id

¥If you inspect the network traffic of a tRPC app, you'll see that it's fairly standard HTTP requests and responses, but you don't need to think about the implementation details while writing your application code. You call functions, and tRPC takes care of everything else. You should ignore details like HTTP Verbs, since they carry meaning in REST APIs, but in RPC form part of your function names instead, for instance: getUser(id) instead of GET /users/:id.

词汇

¥Vocabulary

以下是 tRPC 生态系统中经常使用的一些术语。我们将在整个文档中使用它们,因此熟悉它们是很有好处的。大多数这些概念在文档中也有自己的页面。

¥Below are some terms that are used frequently in the tRPC ecosystem. We'll be using these throughout the documentation, so it's good to get familiar with them. Most of these concepts also have their own pages in the documentation.

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?"