Skip to main content
Version: 10.x

Express 适配器

示例应用

¥Example app

描述链接
使用 Node.js 进行快速服务器和过程调用。

如何将 tRPC 添加到现有 Express 项目

¥How to add tRPC to existing Express project

1. 安装依赖

¥ Install deps

bash
yarn add @trpc/server zod
bash
yarn add @trpc/server zod

Zod 不是必需的依赖,但它在下面的示例路由中使用。

¥Zod isn't a required dependency, but it's used in the sample router below.

2. 创建 tRPC 路由

¥ Create a tRPC router

实现你的 tRPC 路由。下面给出了一个示例路由:

¥Implement your tRPC router. A sample router is given below:

server.ts
ts
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
export const t = initTRPC.create();
export const appRouter = t.router({
getUser: t.procedure.input(z.string()).query((opts) => {
opts.input; // string
return { id: opts.input, name: 'Bilbo' };
}),
createUser: t.procedure
.input(z.object({ name: z.string().min(5) }))
.mutation(async (opts) => {
// use your ORM of choice
return await UserModel.create({
data: opts.input,
});
}),
});
// export type definition of API
export type AppRouter = typeof appRouter;
server.ts
ts
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
export const t = initTRPC.create();
export const appRouter = t.router({
getUser: t.procedure.input(z.string()).query((opts) => {
opts.input; // string
return { id: opts.input, name: 'Bilbo' };
}),
createUser: t.procedure
.input(z.object({ name: z.string().min(5) }))
.mutation(async (opts) => {
// use your ORM of choice
return await UserModel.create({
data: opts.input,
});
}),
});
// export type definition of API
export type AppRouter = typeof appRouter;

如果你的路由文件开始变得太大,请将你的路由拆分为多个子路由,每个子路由都在自己的文件中实现。然后将 合并它们 变成单根 appRouter

¥If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then merge them into a single root appRouter.

3. 使用 Express 适配器

¥ Use the Express adapter

tRPC 包含一个开箱即用的 Express 适配器。该适配器可让你将 tRPC 路由转换为 Express 中间件。

¥tRPC includes an adapter for Express out of the box. This adapter lets you convert your tRPC router into an Express middleware.

server.ts
ts
import { initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
// created for each request
const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => ({}); // no context
type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
// [...]
});
const app = express();
app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
}),
);
app.listen(4000);
server.ts
ts
import { initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
// created for each request
const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => ({}); // no context
type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
// [...]
});
const app = express();
app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
}),
);
app.listen(4000);

你的端点现在可以通过 HTTP 访问!

¥Your endpoints are now available via HTTP!

端点HTTP URI
getUserGET http://localhost:4000/trpc/getUser?input=INPUT

其中 INPUT 是 URI 编码的 JSON 字符串。
createUserPOST http://localhost:4000/trpc/createUser

{name: string} 类型的 req.body