Skip to main content
Version: 10.x

定义路由

要开始构建基于 tRPC 的 API,你首先需要定义路由。一旦掌握了基础知识,你就可以了解更高级的用例。

¥To begin building your tRPC-based API, you'll first need to define your router. Once you've mastered the fundamentals, you can customize your routers for more advanced use cases.

初始化 tRPC

¥Initialize tRPC

你应该为每个应用初始化 tRPC 一次。tRPC 的多个实例会导致问题。

¥You should initialize tRPC exactly once per application. Multiple instances of tRPC will cause issues.

server/trpc.ts
ts
import { initTRPC } from '@trpc/server';
 
// You can use any variable name you like.
// We use t to keep things simple.
const t = initTRPC.create();
 
export const router = t.router;
export const publicProcedure = t.procedure;
server/trpc.ts
ts
import { initTRPC } from '@trpc/server';
 
// You can use any variable name you like.
// We use t to keep things simple.
const t = initTRPC.create();
 
export const router = t.router;
export const publicProcedure = t.procedure;

你会注意到我们在这里导出 t 变量的某些方法而不是 t 本身。这是为了建立一组我们将在代码库中惯用的程序。

¥You'll notice we are exporting certain methods of the t variable here rather than t itself. This is to establish a certain set of procedures that we will use idiomatically in our codebase.

定义路由

¥Defining a router

接下来,让我们定义一个路由,其中包含要在我们的应用中使用的过程。我们现在已经创建了一个 API "endpoint"。

¥Next, let's define a router with a procedure to use in our application. We have now created an API "endpoint".

为了使这些端点暴露给前端,你的 适配器 应该配置有 appRouter 实例。

¥In order for these endpoints to be exposed to the frontend, your Adapter should be configured with your appRouter instance.

server/_app.ts
ts
import { publicProcedure, router } from './trpc';
 
const appRouter = router({
greeting: publicProcedure.query(() => 'hello tRPC v10!'),
});
 
// Export only the type of a router!
// This prevents us from importing server code on the client.
export type AppRouter = typeof appRouter;
server/_app.ts
ts
import { publicProcedure, router } from './trpc';
 
const appRouter = router({
greeting: publicProcedure.query(() => 'hello tRPC v10!'),
});
 
// Export only the type of a router!
// This prevents us from importing server code on the client.
export type AppRouter = typeof appRouter;

高级用法

¥Advanced usage

初始化路由时,tRPC 允许你:

¥When initializing your router, tRPC allows you to:

你可以使用方法链在初始化时自定义 t 对象。例如:

¥You can use method chaining to customize your t-object on initialization. For example:

ts
const t = initTRPC.context<Context>().meta<Meta>().create({
/* [...] */
});
ts
const t = initTRPC.context<Context>().meta<Meta>().create({
/* [...] */
});

运行时配置

¥Runtime Configuration

ts
export interface RuntimeConfig<TTypes extends RootConfigTypes> {
/**
* Use a data transformer
* @link https://trpc.nodejs.cn/docs/data-transformers
*/
transformer: TTypes['transformer'];
/**
* Use custom error formatting
* @link https://trpc.nodejs.cn/docs/error-formatting
*/
errorFormatter: ErrorFormatter<TTypes['ctx'], any>;
/**
* Allow `@trpc/server` to run in non-server environments
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default false
*/
allowOutsideOfServer: boolean;
/**
* Is this a server environment?
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'
*/
isServer: boolean;
/**
* Is this development?
* Will be used to decide if the API should return stack traces
* @default process.env.NODE_ENV !== 'production'
*/
isDev: boolean;
}
ts
export interface RuntimeConfig<TTypes extends RootConfigTypes> {
/**
* Use a data transformer
* @link https://trpc.nodejs.cn/docs/data-transformers
*/
transformer: TTypes['transformer'];
/**
* Use custom error formatting
* @link https://trpc.nodejs.cn/docs/error-formatting
*/
errorFormatter: ErrorFormatter<TTypes['ctx'], any>;
/**
* Allow `@trpc/server` to run in non-server environments
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default false
*/
allowOutsideOfServer: boolean;
/**
* Is this a server environment?
* @warning **Use with caution**, this should likely mainly be used within testing.
* @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'
*/
isServer: boolean;
/**
* Is this development?
* Will be used to decide if the API should return stack traces
* @default process.env.NODE_ENV !== 'production'
*/
isDev: boolean;
}