trpc - Invoking a route from within its own code

After reviewing the information on this page, it appears that you can invoke another route on the server side by utilizing the

const caller = route.createCaller({})
method. However, if the route is nested within itself, is it feasible to achieve this by using the this keyword? If not, what is the alternative approach to calling 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();
  }),
});

Answer №1

Although I may not have the exact answer to your question, based on the provided link for Server Side Calls, it is advised that createCaller should not be utilized to call a procedure from within another procedure.

According to the documentation, using createCaller in this way can lead to unnecessary overhead as it may need to recreate context for each procedure call, even if only one API call is made from the client.

Instead of implementing code like your example:

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

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

It is recommended to use a different approach, such as:

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

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

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

In this revised example, the logic for retrieving the desired information (in this case, just 'hi' but it could be a database query) is abstracted so that the same code is called in each instance without the need for an additional procedure call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on generating a TypeScript class using JSON data

Working with Angular and making a call to an external API. The JSON data is structured as follows: [ { "AccessGroupsIdList": [], "FirstName": "Greg", "LastName": "Tipton", ...

Incorporating HTTP status codes into error handling

I have developed an API where I've organized the services separately from the controllers. In my service functions, I've included basic checks to trigger errors when certain conditions are met. Currently, my controller function just returns a 500 ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

Using the ternary operator in React to implement inline styles

Within my React/Typescript project, I aim to dynamically exhibit a color based on the presence or absence of a value in payload[1]. In the code snippet below, note the usage of an inline style tag. <li className="recharts-tooltip-item" style={ ...

Utilize the global theme feature within React Material-UI to create a cohesive

I'm feeling a bit lost when it comes to setting up React Material-UI theme. Even though I've tried to keep it simple, it's not working out for me as expected. Here is the code snippet I have: start.tsx const theme = createMuiTheme({ ...

An instance of an object is being added instead of parameters

I'm having some trouble making a server call using promises. Whenever I try to add my parameters, they end up showing as 'object%20Object' Here's the code snippet for the call: import { Injectable } from '@angular/core'; imp ...

Navigating with multiple parameters in Angular 7 routing

I am currently facing an issue where I need to navigate to the same component with different parameters. Although I can subscribe to the params through the ActivatedRoute, I'm encountering a problem when trying to call router.navigate within the subsc ...

Retrieving the returned value from an Observable of any type in Angular Typescript (Firebase)

I am working on retrieving data from my Firebase User List using the following code: currentUserRef: AngularFireList<any> currentUser: Observable<any>; var user = firebase.auth().currentUser; this.currentUserRef = this.af.list('usuarios ...

Mastering the art of correctly utilizing splice and slice

I'm having trouble identifying the issue in my code. Despite reading numerous articles on slice and splice, I am unable to achieve the desired outcome in my Angular project (not using both methods simultaneously). The results are not as expected. Belo ...

What is the best way to bundle a TypeScript package along with its dependencies for seamless integration with various Next.js projects on a local environment

Currently, I am immersed in a project with the following arrangement: / # repository root /core # A local, unpublished npm package used by both projectA and projectB /projectA # A Next.js app /projectB # Another Next.js app In my setup, I gene ...

Encountered an error while attempting to compare 'true' within the ngDoCheck() function in Angular2

Getting Started Greetings! I am a novice in the world of Angular2, Typescript, and StackOverflow.com. I am facing an issue that I hope you can assist me with. I have successfully created a collapse animation for a button using ngOnChanges() when the butto ...

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

Unable to make custom font work in TailwindCSS and ReactJS project

I have incorporated a custom font into my projects using React, TypeScript, TailWind, and NextJS. The font file is stored in the /fonts directory with the name Glimer-Regular.ttf. To implement the font, I added the following code snippet to my global.css ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

Exploring .ENV Variables using Angular 2 Typescript and NodeJS

After completing the Angular2 Quickstart and tutorials, I'm now venturing into connecting to a live REST Api. I need to include authentication parameters in my Api call, and from what I've gathered, it's best practice to store these paramete ...

The canActivate function must be responsive to the true or false value of this.authService.isLoggedIn before proceeding

I am facing a problem with my app's routing functionality. When the user logs in with their Google email, I want the app to route to the home page: "". Everything seems to work fine except for the canActivate routeGuard. During the AuthLogin ...

How can different styles be seamlessly combined when customizing Fabric components?

Imagine I am enhancing a Fabric component by adding custom styles and wishing to combine any additional styles passed in through its props. Here's the solution I've devised: const { TextField, Fabric , IButtonProps, mergeStyleSets } = window.Fab ...

Is there a way to remove trigger characters in vscode api completion function?

I am developing a vscode extension that requires custom completion for json files. I would like to know if it is possible to hide the trigger character when using autocompletions. Let me explain further : Imagine the trigger character is '.' In ...

Why is webpack attempting to package up my testing files?

In my project, I have two main directories: "src" and "specs". The webpack configuration entrypoint is set to a file within the src directory. Additionally, the context of the webpack config is also set to the src directory. There is a postinstall hook in ...