0

I have a end-to-end typesafe api using the T3 Stack and I am able to access all the data and types through my Next.js app. But I also have a Node.js backend that I use to populate my database with. My Node.js Settup looks like this:

app.use(
  '/trpc',
  trpcExpress.createExpressMiddleware({
    router: appRouter,
    createContext,
  })
);

app.use('/fund', fundRouter);

Currently I populate the DB by starting the Node server and calling it's self

// Going to http://localhost:3001/fund/create

axios.post('http://localhost:3001/trpc/fund.createManyFunds', data)
.then((x) => x.data)
.catch((e) => e);

But I dont feel like I am utilising the typesafe feature here, I have the type that i can access from my fund.schema.ts export type CreateManyInput = z.TypeOf<typeof createManyFundSchema>; that is being used to get help createing the data for above axios call.

And in the client I can use const trpc = createReactQueryHooks<AppRouter>() from import { createReactQueryHooks } from '@trpc/react'; to make a easy post request

const { mutate, error } = trpc.useMutation(['fund.createManyFunds'], {
  onSuccess: () => {
    console.log("added items");
  },
});

const onSubmit = (values: createManyFundSchema) => {
  mutate(values);
};

But now the questin us how I can do this from the server side. With code above I am able to get intellisense on the path "fund.createManyFunds" but unable to provide data to send with the request.

// Going to http://localhost:3001/fund/create
// Should replace above axios.post request
// Able to create a trpc server "client"?

const client = createTRPCClient<AppRouter>({url: "./"})
client.mutation("fund.createManyFunds", data)  

Is it possible to have this functionality in my node app? Or am I doing it the correct way by using a simple post to my own trpc route?

If it matters I have a NX project that's structured like this App: Node.js server, Next.js client libs: trpc server

PEPEGA
  • 2,214
  • 20
  • 37

1 Answers1

0

You can make a vanilla trpc client:

https://trpc.io/docs/v9/vanilla

Example from the docs:

import type { AppRouter } from '../path/to/server/trpc';
import { createTRPCClient } from '@trpc/client';
const client = createTRPCClient<AppRouter>({
  url: 'http://localhost:5000/trpc',
});
const bilbo = await client.query('getUser', 'id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };
const frodo = await client.mutation('createUser', { name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };
Lawrence Chen
  • 11
  • 1
  • 1