Skip to content

[RFC] Using tRPC for public-facing APIs (OpenAPI/Swagger/etc) #755

Closed

Description

@KATT

👉👉👉👉 Update: For tRPC support of public-facing APIs, please use trpc-openapi: https://github.com/jlalmes/trpc-openapi


It would be nice if there was a way to easily expose tRPC-endpoints as REST (or GraphQL) for people who want to use tRPC for a public API and is a bit more intuitive. Could potentially drive adoption a bit more.

See #752 for an example of what gets confusing.

... been thinking a bit about it, but it's not obvious how it could work.

Maybe doing some sort of API-builder... or something where you define your API schema which then does automatic mapping to tRPC.

I'm also thinking that it might not be needed - JSON.stringify(encodeURIComponent(x)) is hard when you toy around with manual API-requests, but it's not that bad when you're actually working with the API, as it's only needed once.

Current implementation, HTTP Methods <-> Type mapping

HTTP Method Mapping Notes
GET .query() Input JSON-stringified in query param.
e.g. ?input=${JSON.stringify(encodeURIComponent(input))
POST .mutation() Input as post body.

Considerations with OpenAPI

  • Resources are usually /{resource}/{id}?param1=x&param2=y-style - tRPC is [currently] with {resource}?input=JSON.stringify(encodeURIComponent(input))-style
  • JSON-RPC based response shape might not be the ideal response shape for OpenAPI
  • An output schema usually have a $ref-schema which would be possible to do automatically / first feature people would request is to make different paths request the same input type
  • Actually using zod or any other validation on a resolver's output would slow down API outputs.

Related

#271

Activity

  1. changed the title [-][RFC] Using tRPC for public-facing APIs (REST-esque-adapter)[/-] [+][RFC] Using tRPC for public-facing APIs[/+] on Aug 5, 2021
  2. mmkal commented on Aug 20, 2021

    @mmkal
    Contributor

    For local development I've played around with an express middleware that just mutates req.query to make it more "traditional". It only really works for very simple input schemas that are extensions of Record<string, string>, and there may be a whole host of edge-cases, but it's been handy for using postman etc.

    We are using trpc (I feel I should re-iterate - it is so awesome) for our whole API and we likely will have use cases in the pipeline where no-code marketing tools (example), used by non-engineers, need to hit an API of ours using liquid templating to create request urls etc. I think at that point it will be hard to do encodeURIComponent(JSON.stringify({ abc: 'foo' })), although maybe not impossible. It might be pushing the limits of what liquid can do.


    Here's the very dumb middleware that converts regular query params into TRPC-friendly format (haven't considered batching or anything like that since this is just for localhost prototyping):

    app.use((req, _res, next) => {
      // stupid middleware that, on localhost, rewrites `/foo?.x=abc&.y=def` to `/foo?input=${encodeURIComponent(JSON.stringify({x: 'abc', y: 'def'}))}` which is much harder to construct from postman!
      if (req.hostname !== 'localhost' || req.headers['user-agent']?.match(/Mozilla/)) {
        next()
        return
      }
    
      let input: any
      Object.keys(req.query)
        .filter(k => k.startsWith('.'))
        .forEach(k => {
          input ||= {}
          input[k.replace('.', '')] = req.query[k]
        })
    
      if (input) {
        req.query.input = JSON.stringify(input)
      }
    
      next()
    })
  3. added
    🙋‍♂️ help wanted
    on Aug 21, 2021
  4. danielyogel commented on Aug 31, 2021

    @danielyogel

    I wonder if keeping the tRPC’s endpoint definition clean and mostly “just write TypeScript” (as they are now), then adding something like “API_STYLE” with values of Array<REST/GraphQL/tRPC>, as a per route (and/or per server) option - would be nice.

    As a more “advanced” option, a “transformToAPI” and “transformFromAPI” hooks may help, but I would defer this implementation, as most people just need REST/GraphQL/tRPC…

  5. KATT commented on Sep 3, 2021

    @KATT
    MemberAuthor

    @danielyogel this is sort of the approach I've been thinking of too - allowing to have an "OpenAPI-builder" that is a separate package. Would probably be possible to use something like tsoa or openapi-typescript and then map the Swagger schema to specific procedures in your trpc-router

  6. akomm commented on Sep 20, 2021

    @akomm

    I don't think RPC fits into GraphQL or Rest in terms of automation. I think any attempt to do it would end up in an endless spiral of people having issues. I don't say you can't map to it, just that its complex to automate to fit all the demands that will come at you ;).

    Still great respect for taking anything into consideration and asking people! :)

  7. benbender commented on Sep 20, 2021

    @benbender

    I would agree that it might be a lost cause to try to support Graphql and/or Rest within their own semantics. Rest has the relation between url and object, which an RPC-style interface don't have.
    A full-fledged GraphQL-Server on the other hand needs a query-engine which constructs the result based on the query from within the client - also unknown to an rpc-style server.

    So it might be solution to not to try (and advertise) full support for either of those, but handle it more like another transport on top of trpc. So it could be possible to simply add a graphql-endpoint on top of an existing trpc-server to use it via existing-client/tooling.

    Usecases could be f.e., as said, reusing existing clients or to use smth graphql-federation, graphql-mesh etc.

  8. akomm commented on Sep 20, 2021

    @akomm

    So it could be possible to simply add a graphql-endpoint on top of an existing trpc-server to use it via existing-client/tooling

    I don't see how it fits in a fashion which could be automated to produce any meaningful API based on this. Maybe we need to work with examples and figure out a way.

    Given this return from a query (we reduce the issue to just the return type as a starter)

    type QueryResult = {type: "A"; x: number} | {type: "B"; s: string}

    What would be the graphql type for that? Consider type is an arbitrary discriminant and you might also have more than one.

    I actually even think, that REST might even be more close to TRPC than GraphQL.

  9. benbender commented on Sep 20, 2021

    @benbender

    I don't see how it fits in a fashion which could be automated to produce any meaningful API based on this. Maybe we need to work with examples and figure out a way.

    I was thinking about generating the queries/mutations based on the trpc-api (f.e. using graphql-codegen) in a direct mapping. So it wouldn't be possible to create your own, arbitrary queries/mutations, but you would have a one-to-one mapping to the ones defined in the trpc-routers. Basically every method would get its own input- and output-type in graphql-land. In my mental model I've tried to simplify as much as possible to solve the "issue-spiral" you had (imho correctly) in mind.

    Given this return from a query (we reduce the issue to just the return type as a starter)

    type QueryResult = {type: "A"; x: number} | {type: "B"; s: string}

    Would simply be

    type AResult {
      x: number;
    }
    
    type BResult {
      s: string;
    }
  10. akomm commented on Sep 21, 2021

    @akomm

    First thing I want to mention is. I let it go through my head with the mental mode of "how could it work" and not "what problems are there". I merely represent the result or problems I still encoutered and could not "fix".

    On first glance you can map TRPC query/mutation/subscription names into the graphql world by replacing invalid characters in TRPC names with accepted in GraphQL spec. However, this is not exactly correct. You need to evaluate it as two sets of - in this case unicode code points - allowed by either side.

    You can figure out the size of the set on graphql side via the ebnf in the spec:
    https://spec.graphql.org/draft/#sec-Names

    And I can tell you without looking, that the set in js/ts "string" token will be much larger. I'v onced checked on this, but you can even logically derive it, knowing both languages. If you map from one set into another which is smaller, you will have collisions. Its like hashing an non-finite set of possible strings using a hashing alg. of a finite set of elements it provides via its fixed length. You will have different names in TRPC mapped to same name in GraphQL.

    You could semi-solve it by for example providing some sort oft map of certain characters you want to use in your trpc names to valid replacements in graphql. On codegeneration you could then disallow to generate same name twice and throw if that happens... You can also map to a smaller set via encoding (for example base64 does it). This has the cost of removing any readability (would be hard to preserve it) and increasing the size of the output, because it has to use unique sequences to represent the larger set. And there starts the spiral. All in all, the output naming would be sub-optimal and opinionated at best, if you still do any of this.

    Regarding the example types, I'v noticed a few things.

    • You make an asumption that I don't need the information in field type and instead use __typename (I guess). Also: If the generator outputs a different type name, it would break clients using __typename.
    • You might have another discriminate candidate, for example:
    type QueryResult = {type: "A"; x: number, a: true} | {type: "B"; s: string b: false}
    • QueryResult could have generics. Evtl. solvable, similar to name mangling for generics done in other languages. But it would generate many intermediate types as a side-effect.
    • Type aliases in TS are more complicated. Even TS itself had many changes in terms of how it decides to show the names in type errors, to make it simpler to find a source. What if you had this defined, what name would the type: "B" be given automatically :
    type QueryResult = XandTrueResult | {type: "B"; s: string b: false}

    One thing in common I find is, that the output would be very bad API, both on field naming and type naming. The question I finaly ended at is: what is the point of producing it? It appears simpler to just create an graphql endpoint and map things using code. You have a total control of how you map. Actually, if you don't implement your APPs logic entirely in TRPC's resolve functions, you should be able to simply map to the same functions from graphql's resolve.

  11. changed the title [-][RFC] Using tRPC for public-facing APIs[/-] [+][RFC] Using tRPC for public-facing APIs (OpenAPI/Swagger/etc)[/+] on Sep 26, 2021
  12. derolf commented on Oct 25, 2021

    @derolf

    Is there a way to generate a JSON-SPEC or similar from an AppRouter?

  13. jlalmes commented on Jun 10, 2022

    @jlalmes
    Contributor
  14. locked and limited conversation to collaborators on Jun 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions