Hacker News new | past | comments | ask | show | jobs | submit login

A large part of GraphQL is the idea of tightly coupling queries to code, declaratively, combined with smart differential logic.

The original web framework for GraphQL was Facebook's Relay, which essentially lets you declare, in your component, what data you want. Relay stitches together your query and avoids work by figuring out the difference between what data the client has (in its cache) and hasn't.

Apollo's React framework is based around the same ideas. You're supposed to declare the query privately in the component that needs it, and in principle, caching should avoid many unnecessary fetches. For example, if you have:

  // In component A
  {
    currentUser { id, name }
    topStories { id, title }
  }

  // In component B
  {
    currentUser { name }
    favouriteTopics { id, name }
  }
then the delta from A to B is { favouriteTopics { id, name } }, and no re-fetching of currentUser is needed, since it is a subset that merely needs to be filtered.

(There are of course ways to write queries that will always conflict with each other, e.g. by applying different parameters such as filters to nested fields.)

In practice, I'm not sure if Apollo is that smart yet. I think it currently considers any difference in field selections to be a conflicting change, even strict subsets, but I could be wrong.

When used outside of React, GraphQL becomes more like SQL:

  for (const {name} of (await query(gql`{
    users { id, name }
  }`)).users {
    // ...
  }



Theoretically, a smart enough GraphQL front-end could recognize multiple filters and do some or all of the filtering client-side, or if impossible, request both from the server. The idea that your client can declare what data it needs rather than leaving it up to the server is the best part of GraphQL, the thing that simplified it the most. But it’s hard to do well, right now. It’s much easier to use code-gen directly to have client and server share knowledge of what’s needed. HTTP2 push adds an interesting twist though, when your GraphQL response could actually trigger additional client code and resources to be sent. Of course this can be done without GraphQL, but you’d still need a server that’s aware of what data the client will use and how. For simple APIs or APIs with many clients that behave the same way, GraphQL is overkill. But even so it’s an interesting alternative to simple REST and simple state management, and unlike Redux, you can trigger multiple events at the same time which can be beneficial if processing their state changes at the same time would lead to a more efficient update. (The Redux alternative is to add some kind of wrapper event, or an event for each combination of events...)




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: