Call route within route in server

How can I call a route in a different route. For example I have this route:
export const realEstateRouter = router({
create: protectedProcedure
.input(createRealEstateSchema)
.mutation(async ({ ctx, input }) => {
...
export const realEstateRouter = router({
create: protectedProcedure
.input(createRealEstateSchema)
.mutation(async ({ ctx, input }) => {
...
I want to call that create function in a different route like this:
import { createUserActivitySchema } from "@/validation/user-activity";
import { protectedProcedure, router } from './../trpc';

export const userActivityRouter = router({
create: protectedProcedure
.input(createUserActivitySchema)
.query(async ({ ctx, input }) => {

const userId = ctx.auth.userId;

if (!userId) throw new Error('User is not authenticated');

const result = await ctx.prisma.userActivity.create({
data: {
...input,
user: {
connect: {
userId: userId
}
}
}
})

return result;
}),
});
import { createUserActivitySchema } from "@/validation/user-activity";
import { protectedProcedure, router } from './../trpc';

export const userActivityRouter = router({
create: protectedProcedure
.input(createUserActivitySchema)
.query(async ({ ctx, input }) => {

const userId = ctx.auth.userId;

if (!userId) throw new Error('User is not authenticated');

const result = await ctx.prisma.userActivity.create({
data: {
...input,
user: {
connect: {
userId: userId
}
}
}
})

return result;
}),
});
But that does not work, any ideas?
3 Replies
whatplan
whatplan2y ago
Server Side Calls | tRPC
You may need to call your procedure(s) directly from the same server they're hosted in, router.createCaller() can be used to achieve this.
Christopher Ehrlich
YouTube
Advanced tRPC - Callers, functions, and gSSP
🚨 createSSGHelpers has been renamed to createServerSideHelpers 🚨 Repo for this video: https://github.com/c-ehrlich/you-dont-need-callers If you want to use schema in the frontend, they cannot be imported from the same file as things that run specifically in the backend. One solution would be to put them into a procedureName.schema.ts or simi...
whatplan
whatplan2y ago
tdlr you probably dont want to call your own backend from your backend extract the shared logic into a single external function you call from both places
zenith
zenith2y ago
TRPC specifically recommends against calling other routes within routes even using the server side stuff
Want results from more Discord servers?
Add your server