You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于tRPC路由内部调用自身及兄弟路由的实现方法问询

在tRPC路由内部调用自身或兄弟路由的实现方式

关于this关键字的使用

直接在路由procedure里用this.createCaller()是行不通的——tRPC的procedure上下文里的this并不指向当前的router实例,这么写会直接报错,别浪费时间试这个路子。

推荐的实现方案

1. 把路由逻辑抽成独立函数(最推荐)

把需要复用的业务逻辑从procedure里拆出来,不管是自身调用还是兄弟路由调用,直接调用函数就行,既高效又避免各种上下文问题:

import { z } from "zod";
import { router, publicProcedure } from "../trpc";

// 抽离可复用的业务逻辑
const getHi = async () => "Hi there!";
const getWorld = async () => "World";

export const exampleRouter = router({
  hi: publicProcedure.query(getHi),
  world: publicProcedure.query(getWorld),
  hello: publicProcedure.query(async () => {
    // 直接调用抽离的函数
    const hiText = await getHi();
    const worldText = await getWorld();
    return `${hiText} ${worldText}`;
  }),
});

2. 先声明router再创建caller

如果必须要通过caller调用(比如需要走中间件逻辑),可以先声明router类型,再初始化router,最后通过闭包访问router实例创建caller:

import { z } from "zod";
import { router, publicProcedure } from "../trpc";

// 先声明router的类型,避免TS报错
let exampleRouter: ReturnType<typeof router>;

exampleRouter = router({
  hi: publicProcedure.query(async () => "Hi there!"),
  world: publicProcedure.query(async () => "World"),
  hello: publicProcedure.query(async () => {
    // 创建caller并调用兄弟路由
    const caller = exampleRouter.createCaller({});
    const hiText = await caller.hi();
    const worldText = await caller.world();
    return `${hiText} ${worldText}`;
  }),
});

export default exampleRouter;

注意:这种方式会让caller走完整的中间件流程,如果不需要中间件处理,还是用第一种方案更高效。

内容的提问来源于stack exchange,提问作者wongx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:10:49