Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a createTRPCOpenApiClient #33

Open
czeidler opened this issue Aug 15, 2024 · 3 comments
Open

Add a createTRPCOpenApiClient #33

czeidler opened this issue Aug 15, 2024 · 3 comments

Comments

@czeidler
Copy link

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' })
@Vercjames
Copy link
Owner

Vercjames commented Sep 3, 2024

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.

@czeidler
Copy link
Author

czeidler commented Sep 4, 2024

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.

@Vercjames
Copy link
Owner

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants