0

Based on the documentation here, you can call another route on the server side using the const caller = route.createCaller({}) function. However, if the route is within itself, is it possible to do so using the this keyword? If not, how can one call a route sibling?

import { z } from "zod";

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

export const exampleRouter = router({
  hi: publicProcedure.query(async () => {
    return "Hi there!";
  }),
  world: publicProcedure.query(async () => {
    return "World";
  }),
  hello: publicProcedure.query(async function () {
    const caller = this.createCaller({});
    const result = await caller.example.hi();
  }),
});

esqew
  • 42,425
  • 27
  • 92
  • 132
wongz
  • 3,255
  • 2
  • 28
  • 55

1 Answers1

1

While I don't know the answer to the exact question you asked, based on the link you provided for Server Side Calls, createCaller should not be used to call a procedure from within another procedure.

The documentation mentions that this will create overhead as it may need to create context again for each procedure call even if only one API call was made from the client.

So instead of something like your example code:

import { procedure, router } from '../trpc'

export const myRouter = router({
    hi: procudure.query(() => 'hi'),
    hello: procedure.query(() => {
        const caller = createCaller({})
        return caller.myRouter.hi()
    })
})

You should be doing something like this:

import { procedure, router } from '../trpc'

const getHi = () => {
    return 'hi'
}

export const myRouter = router({
    hi: procudure.query(() => getHi()),
    hello: procedure.query(() => getHi())
})

In that example, the logic used to get the information you want (just 'hi' in this case but it could be a database call) is abstracted so that in each case you still call the same code, but without the additional procedure call.

laycalva
  • 11
  • 1