tRPCttRPC
Powered by
ididitI
tRPC•2y 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();
      }),
  });
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);
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,
      }),
    );
  }
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?
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Can't I create multiple TRPC React using same Router?
kevinkaKkevinka / ❓-help
3y ago
how to proxy a router
PKPPK / ❓-help
2y ago
JSON inferred router output not matching
rdRrd / ❓-help
3y ago