package-trpc-swagger icon indicating copy to clipboard operation
package-trpc-swagger copied to clipboard

Add a createTRPCOpenApiClient

Open czeidler opened this issue 1 year ago • 3 comments

This would be useful if you want to have a public OpenApi api, but also want to do REST calls in your own code where you have the tRPC types available, i.e. no OpenApi client code needs to be generated because you can just use tRPC.

For example:

// do a REST call using tRPC:
const trpc = createTRPCOpenApiClient<AppRouter>({ url: 'localhost:8080'})
const helloResponse = await trpc.hello.query({
    name: 'world',
});

// which is equivalent to:
await fetch('http://localhost:8080/hello?name=world', { method: 'GET' })

czeidler avatar Aug 15 '24 12:08 czeidler

LMK if this solves the issue.

Next.js project

app/api/[...trpc]/route.ts

import { AppRouter } from "@/server/router"
import { createOpenApiFetchHandler } from "trpc-swagger"
import { CreateContext } from "@/server/trpc-utils/trpc-context"

const restHandler = (request: Request) => {
  // VERC: Handle incoming swagger/openapi requests
  return createOpenApiFetchHandler({
    req: request,
    router: AppRouter,
    endpoint: "/api",
    createContext: CreateContext,
  })
}
export {
  restHandler as DELETE,
  restHandler as GET,
  restHandler as PATCH,
  restHandler as POST,
  restHandler as PUT,
}

Now my app can use axios or fetch requests.

Vercjames avatar Sep 03 '24 15:09 Vercjames

I mean doing client API requests using trpc by transparently translating the trpc api call (e.g. trpc.hello.query()) to a REST call. So that you still got all the trpc type safety on the client but instead of the trpc protocol you use a REST like protocol.

czeidler avatar Sep 04 '24 10:09 czeidler

@czeidler Feel free to remind me about this feature when I release TRPC v11. I like the idea and am open to exploring ways to eliminate the redundant need for including base fetch requests. It would be great if we could achieve type safety for standard REST API requests without relaying on a specific client side definition.

Vercjames avatar Sep 10 '24 16:09 Vercjames