跳至主内容
版本:9.x

快速入门

非官方测试版翻译

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

技巧

强烈建议您先浏览示例应用,这将帮助您直观感受 tRPC 的运作方式并实现无缝上手。

安装

⚠️ 要求:tRPC 需要 TypeScript > 4.1 版本,因其依赖模板字面量类型

npm install @trpc/server

用于实现 tRPC 端点和路由器。请安装在服务端代码库中。

npm install @trpc/client @trpc/server

用于在客户端发起类型安全的 API 调用。请安装在客户端代码库中(@trpc/server@trpc/client 的 peer 依赖项)。

npm install @trpc/react react-query@3

用于生成强大的 React Hooks 来查询 tRPC API。基于 react-query 实现。

npm install @trpc/next

提供与 Next.js 集成的实用工具集。

安装代码片段

npm:

bash
npm install @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next
bash
npm install @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next

yarn:

bash
yarn add @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next
bash
yarn add @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next

定义路由器

下面我们将逐步构建类型安全的 tRPC API。初始阶段该 API 仅包含两个端点:

ts
getUser(id: string) => { id: string; name: string; }
createUser(data: {name:string}) => { id: string; name: string; }
ts
getUser(id: string) => { id: string; name: string; }
createUser(data: {name:string}) => { id: string; name: string; }

创建路由器实例

首先在服务端代码库中定义路由器:

server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router();
// only export *type signature* of router!
// to avoid accidentally importing your API
// into client-side code
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router();
// only export *type signature* of router!
// to avoid accidentally importing your API
// into client-side code
export type AppRouter = typeof appRouter;

添加查询端点

使用 .query() 方法向路由器添加查询端点。参数说明:

.query(name: string, params: QueryParams)

  • name: string:端点名称

  • params.input:可选。该函数用于验证/转换端点的输入值,应返回强类型数据(验证通过)或抛出错误(验证失败)。也可传入 ZodSuperstructYup 的验证模式。

  • params.resolve:端点的实际实现函数。接收包含 req 参数的单一对象,其中已验证的输入值位于 req.input,上下文信息位于 req.ctx(稍后详述上下文机制)。

server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
});
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
});
export type AppRouter = typeof appRouter;

添加变更端点

与 GraphQL 类似,tRPC 区分查询端点和变更端点。现在添加 createUser 变更端点:

ts
createUser(payload: {name: string}) => {id: string; name: string};
ts
createUser(payload: {name: string}) => {id: string; name: string};
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
const appRouter = trpc
.router()
.query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
})
.mutation('createUser', {
// validate input with Zod
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
// use your ORM of choice
return await UserModel.create({
data: req.input,
});
},
});
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
const appRouter = trpc
.router()
.query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
})
.mutation('createUser', {
// validate input with Zod
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
// use your ORM of choice
return await UserModel.create({
data: req.input,
});
},
});
export type AppRouter = typeof appRouter;

后续步骤

tRPC 提供了更高级的客户端工具,专为 React 项目(特别是 Next.js)设计。请继续阅读相关指南: