Deepak Sharma
Deepak Sharma4mo ago

Nested tRPC procedures.

I'm trying to convert a REST API structure to tRPC. Specifically, I want to replicate the nested REST route products/:productId/discount in tRPC ? . How should I declare and organize these nested routes in tRPC to match this structure effectively?
Solution:
there is no reason for the nesting here because you only have one procedure inside the nested routers
Jump to solution
12 Replies
Deepak Sharma
Deepak SharmaOP4mo ago
No description
Ahmed Elsakaan
Ahmed Elsakaan4mo ago
trpc.products.discount?
Deepak Sharma
Deepak SharmaOP4mo ago
like should i nest a router into another ?
import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";
import { z } from "zod";

const productsRouter = createTRPCRouter({
get: publicProcedure
.input(z.object({ productId: z.string() }))
.query(async ({ input }) => {
const { productId } = input;
// Fetch product by ID logic here
}),
// Nested router for handling discounts related to a specific product
discount: createTRPCRouter({
get: publicProcedure
.input(z.object({ productId: z.string() }))
.query(async ({ input }) => {
const { productId } = input;
}),
}),
});

export default productsRouter;
import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";
import { z } from "zod";

const productsRouter = createTRPCRouter({
get: publicProcedure
.input(z.object({ productId: z.string() }))
.query(async ({ input }) => {
const { productId } = input;
// Fetch product by ID logic here
}),
// Nested router for handling discounts related to a specific product
discount: createTRPCRouter({
get: publicProcedure
.input(z.object({ productId: z.string() }))
.query(async ({ input }) => {
const { productId } = input;
}),
}),
});

export default productsRouter;
Solution
Ahmed Elsakaan
Ahmed Elsakaan4mo ago
there is no reason for the nesting here because you only have one procedure inside the nested routers
Ahmed Elsakaan
Ahmed Elsakaan4mo ago
also with trpc, there is no one set guideline, organise it the way you like basically 😅
Deepak Sharma
Deepak SharmaOP4mo ago
you mean i can use trpc.product.getDiscount ?
Ahmed Elsakaan
Ahmed Elsakaan4mo ago
yeah
Deepak Sharma
Deepak SharmaOP4mo ago
thanks Ahmed
Ahmed Elsakaan
Ahmed Elsakaan4mo ago
no worries
Deepak Sharma
Deepak SharmaOP4mo ago
if you have anytrpc best practices docs or articles please do share with me.
Ahmed Elsakaan
Ahmed Elsakaan4mo ago
the one I would give is, start with one router until it feels complex enough to need to split/nest it
Deepak Sharma
Deepak SharmaOP4mo ago
sounds great!