Update 18 Feb 2017: For a zero-dependency improvement of this concept, see f/graphql-js.
The endpoint accepts a few parameters:
query: The GraphQL query string to execute
variables: Runtime values for variables in the GraphQL query
querycontains multiple operations, you must tell the server which one to execute
Given this interface, you can even use jQuery as a GraphQL client! Here’s how you would use
$.post to interact with the server.
1. Build and send query strings
For example, if you were searching users by name, you might use this function to build a query string:
1 2 3 4 5 6 7
Then, you can post the query with
1 2 3 4 5 6 7 8
In the callback, you can check for errors and use the response’s
2. Send query and variables
Often, we know our data requirements ahead of time. That is, we know what values we need to render our UI. In this case, we can separate the query structure and runtime values into
Here’s how we could adapt our previous example to separate the query from its values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
In this case, we always send the same query string, but we change the
variables for each request.
This setup is easier to maintain because the query string is so easy to read. Any changes to it will be easy to see in a pull request.
3. (future) Store query strings on the server
Maybe you noticed an optimization waiting to happen: since we always send the same query string, why send it at all? We could store it on the server ahead of time, then call it by name at runtime.
I heard that Facebook’s GraphQL server had this behavior, but I don’t know that any of the open implementations have it yet. I’m considering it for