trpc / v10-playground

tRPC v10 procedure play
https://stackblitz.com/github/trpc/v10-playground?file=src%2Fserver%2Findex.ts,src%2Fclient.ts,src%2Fserver%2Frouters%2FpostRouter.ts&view=editor
13 stars 3 forks source link

Make the RPC call as property access on the Proxy #21

Closed KATT closed 2 years ago

KATT commented 2 years ago

Fork of #17

Allows you to call your API like this:

import type { appRouter } from './server';
import { createClient } from '@trpc/client';

const client = createClient<typeof appRouter>();

async function main() {
  // you can CMD+click `postById` here and jump straight into your backend
  const byId = await client.query.postById({ id: '1' });

  if (byId.ok) {
    console.log('data', byId.data);
  } else {
    console.log(byId.error.code);
  }
}

main();

Upsides

Downsides

esamattis commented 2 years ago

Really cool!

We're actually lying to the compiler

Does it matter if it is just the internals? Should not affect the users in any way? 🤔

KATT commented 2 years ago

Does it matter if it is just the internals? Should not affect the users in any way? 🤔

In some cases it might, if they miss using the proxy object for instance or are doing backend-stuff and trying to explicitly call the functions

KATT commented 2 years ago

Furthermore... Wondering how the React-api could look like. I've noticed that when I try to remap functions, I seem to lose CMD+click ability...

A few options

// this is a bit ugly but will work to do CMD+click on `greeting` with to jump to the backend
const { queries } = myQueries
trpc.useQuery(queries.greeting({ name: 'world' }), { /* .. further options */})

// these below won't work to CMD+click on :(
trpc.useQuery.greeting({ name: 'world' }, { /* .. further options */})
trpc.useGreetingQuery({ name: 'world' }, { /* .. further options */})
KATT commented 2 years ago

@colinhacks maybe you have ideas/input on the above?

esamattis commented 2 years ago

@KATT

In some cases it might, if they miss using the proxy object for instance or are doing backend-stuff and trying to explicitly call the functions

Hmm, direct proxy usage might a bit too magical. Explicit query argument does indeed communicate better that there's something more than just a function call going on.

And if it does not work out for the React hook, there some value having them be consistent:

client.query(query.greeting, { name: "world" });
useQuery(query.greeting, { name: "world" });
KATT commented 2 years ago

Merging for now - can be discussed in #26