Hacker News new | ask | show | jobs
by shurcooL 3242 days ago
Question, how well do GraphQL APIs compose?

For example, imagine I define my GraphQL schema which is pretty similar to another GraphQL schema (of a remote API server).

Could I implement my GraphQL server's resolvers in such a way that they simply rewrite/reinterpret the incoming query by forwarding the (modified) query to the target remote GraphQL server? Or will it be very inefficient and very hard to write this kind of GraphQL-schema-to-similar-GraphQL-schema adapter?

To compare REST, one can imagine (a part of) your REST API being similar to another external REST API. It's relatively straightforward to have your HTTP handlers map to remote REST API endpoints and make the neccessary conversions. (Assuming your REST endpoints map relatively 1:1 to the other API's REST endpoints).

Hopefully my question makes sense...

2 comments

I'm still fairly new to GraphQL, so take this with a grain of salt, but it's my understanding that a idiomatic GraphQL server would implement a single purpose resolver function for _every single field_ in the schema, and these field resolvers would then compose together to resolve larger query fragments. Often a request caching & batching layer like Facebook's own DataLoader library is necessary to make data fetching efficient and performant under this model: http://graphql.org/learn/best-practices/#server-side-batchin...

So in other words, for parts of your schema that are similar to each other, you'd simply include and compose together the relevant resolver functions for the fields they share. The conceptual model is similar to reducer composition in Redux, where top-level reducers (analogous to the root query resolver in GraphQL) can delegate to child reducers each responsible for only a part of the application state (or child resolvers each responsible for resolving a single fragment of the whole query), and this delegation can continue to arbitrary depths.

EDIT: I see your question is actually about composing with third party GraphQL APIs, so I haven't really answered it. GraphQL resolvers are just functions that return data. So you can certainly just implement an async resolver that forwards the received GraphQL query to a remote API of interest, and take the response returned and merge/override it with additional data to form the response to your own query.

Depending on what you're looking for, it might not be straightforward with the normal high level utilities, but most libraries also provide lower level functions for parsing and such.

If you just want to grab an object for a certain edge than that's easy. Routing the entire query differently based on something at the root would also be easy, but routing it based on something deeply nested might be trickier, but still not too tricky.