ididitI
tRPC17mo ago
1 reply
ididit

how can i create a router off of a JSON?

is it possible to create a route dynamically off of a JSON?
lets say i have:

appRouter = this.trpc.router({
    findUser: this.trpc.procedure
      .input(z.object({ name: z.string().optional() }))
      .query(({ input }) => {
        return this.userService.findUser({ name: input.name });
      }),
    findUsers: this.trpc.procedure
      .query(({ input }) => {
        return this.userService.findUsers();
      }),
  });


but i want this created dynamically from a JSON that looks something like this:

const routes = [
      {
        name: 'fetchUsers',
        input: { name: z.string() },
        type: 'query',
      },
      {
        name: 'createUser',
        input: { name: z.string() },
        type: 'mutation',
      },
    ];
... convert routes to procedures ...
this.appRouter = this.router(procedures);


afterwards i applied the routes to the middleware and it works on backend:
public async applyMiddleware(app: any) {
    app.use(
      '/trpc',
      trpcExpress.createExpressMiddleware({
        router: this.appRouter,
      }),
    );
  }


but from the client-side, i lost all type inference to these routes. anyone ever get this to work?
Was this page helpful?