<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dhaivat Pandya on Medium]]></title>
        <description><![CDATA[Stories by Dhaivat Pandya on Medium]]></description>
        <link>https://medium.com/@dpandya?source=rss-c066cfeacf95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DTwRRq2NgQjI55-kG3hWTQ.jpeg</url>
            <title>Stories by Dhaivat Pandya on Medium</title>
            <link>https://medium.com/@dpandya?source=rss-c066cfeacf95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 05:21:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dpandya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Modularizing your GraphQL schema code]]></title>
            <link>https://medium.com/apollo-stack/modularizing-your-graphql-schema-code-d7f71d5ed5f2?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7f71d5ed5f2</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apollo-server]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 14:27:52 GMT</pubDate>
            <atom:updated>2018-04-12T14:29:28.863Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to split up your schema definition, resolvers, and Query type into multiple files</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4If-QCJPmB6SJV9EyNTsmw.png" /></figure><p>As your GraphQL application grows from demo, to proof of concept, to production, the complexity of your schema and resolvers will grow in tandem. To organize your code, you’ll want to split up your schema types and the associated resolvers into multiple files.</p><p>We get this question frequently since there are a lot of different approaches to splitting up your schema code, and it might seem that you need a complex setup to get a good result. But it turns out that we can arrange our schema and resolver code in separate files with just a few simple JavaScript concepts.</p><p>In this post, we present a straightforward method for modularizing schemas built with graphql-tools that you can tweak to match your tastes and your codebase.</p><h3>Schema</h3><p>If you’re just starting out and have your entire schema defined in one file, it might look much like the below snippet. Here, we’ll call it schema.js:</p><pre>// schema.js</pre><pre>const typeDefs = `<br>  type Query {<br>    author(id: Int!): Post<br>    book(id: Int!): Post<br>  }</pre><pre>  type Author {<br>    id: Int!<br>    firstName: String<br>    lastName: String<br>    books: [Book]<br>  }</pre><pre>  type Book {<br>    title: String<br>    author: Author<br>  }<br>`;</pre><pre>makeExecutableSchema({<br>  typeDefs: typeDefs,<br>  resolvers: {},<br>});</pre><p>Ideally, instead of having everything in one schema definition string, we’d like to put the schema types for Author and Book in files called author.js and book.js.</p><p>At the end of the day, the schema definitions we’ve written in the Schema Definition Language (SDL) are just strings. Treating them as such, we have a simple way of importing type definitions across different files: Split up the string into multiple strings that we can combine later. This is what author.js would look like:</p><pre>// author.js<br>export const typeDef = `<br>  type Author {<br>    id: Int!<br>    firstName: String<br>    lastName: String<br>    books: [Book]<br>  }<br>`;</pre><p>Here’s book.js:</p><pre>// book.js<br>export const typeDef = `<br>  type Book {<br>    title: String<br>    author: Author<br>  }<br>`;</pre><p>Finally, we pull it all together in schema.js:</p><pre>// schema.js<br>import { typeDef as Author } from &#39;./author.js&#39;;<br>import { typeDef as Book } from &#39;./book.js&#39;;</pre><pre>const Query = `<br>  type Query {<br>    author(id: Int!): Post<br>    book(id: Int!): Post<br>  }<br>`;</pre><pre>makeExecutableSchema({<br>  typeDefs: [ Query, Author, Book ],<br>  resolvers: {},<br>});</pre><p>We’re not doing anything fancy here: we’re just importing strings that happen to contain some SDL. Note that for convenience you don’t need to combine the strings yourself — makeExecutableSchema can actually accept an array of type definitions directly to facilitate this approach.</p><h3>Resolvers</h3><p>Now that we have a way to chop up our schema into logical parts, we want to be able to move each resolver with its associated part of the schema as well. In general, we want to keep resolvers for a certain type in the same file as the schema definition for that type.</p><p>Expanding on our previous example, here’s our schema.js file with some resolvers added into the picture:</p><pre>// schema.js<br>import { typeDef as Author } from &#39;./author.js&#39;;<br>import { typeDef as Book } from &#39;./book.js&#39;;</pre><pre>const Query = `<br>  type Query {<br>    author(id: Int!): Post<br>    book(id: Int!): Post<br>  }<br>`;</pre><pre>const resolvers = {<br>  Query: {<br>    author: () =&gt; { ... },<br>    book: () =&gt; { ... },<br>  },<br>  Author: {<br>    name: () =&gt; { ... },<br>  },<br>  Book: {<br>    title: () =&gt; { ... },<br>  },<br>};</pre><pre>makeExecutableSchema({<br>  typeDefs: [ Query, Author, Book ],<br>  resolvers,<br>});</pre><p>Just like we split up the schema definition string, we can split up the resolvers object. We can put a piece of it in author.js, another in book.js, and then import them and use the lodash.merge function to put it all together in schema.js.</p><p>Here’s what author.js would look like in that case:</p><pre>// author.js<br>export const typeDef = `<br>  type Author {<br>    id: Int!<br>    firstName: String<br>    lastName: String<br>    books: [Book]<br>  }<br>`;</pre><pre>export const resolvers = {<br>  Author: {<br>    books: () =&gt; { ... },<br>  }<br>};</pre><p>Here’s book.js:</p><pre>// book.js<br>export const typeDef = `<br>  type Book {<br>    title: String<br>    author: Author<br>  }<br>`;</pre><pre>export const resolvers = {<br>  Book: {<br>    author: () =&gt; { ... },<br>  }<br>};</pre><p>Then, we apply lodash.merge in schema.js to put everything together:</p><pre>import { merge } from &#39;lodash&#39;;</pre><pre>import { <br>  typeDef as Author, <br>  resolvers as authorResolvers,<br>} from &#39;./author.js&#39;;</pre><pre>import { <br>  typeDef as Book, <br>  resolvers as bookResolvers,<br>} from &#39;./book.js&#39;;</pre><pre>const Query = `<br>  type Query {<br>    author(id: Int!): Author<br>    book(id: Int!): Book<br>  }<br>`;</pre><pre>const resolvers = {<br>  Query: { <br>    ...,<br>  }<br>};</pre><pre>makeExecutableSchema({<br>  typeDefs: [ Query, Author, Book ],<br>  resolvers: merge(resolvers, authorResolvers, bookResolvers),<br>});</pre><p>And that gives us the resolvers structure that we started out with!</p><h3>Extending types in multiple files</h3><p>We’re still defining authors and books as top-level fields on Query within schema.js, even though these are logically tied to Author and Book and should live in author.js and book.js.</p><p>To accomplish that, we can use type extensions. We can define our existing Query type like this:</p><pre>const Query = `<br>  type Query {<br>    _empty: String<br>  }<br>  <br>  extend type Query {<br>    author(id: Int!): Author <br>  }<br>  <br>  extend type Query {<br>    book(id: Int!): Book <br>  }<br>`;</pre><p><em>Note: In the current version of GraphQL, you can’t have an empty type even if you intend to extend it later. So we need to make sure the Query type has at least one field — in this case we can add a fake _empty field. Hopefully in future versions it will be possible to have an empty type to be extended later.</em></p><p>Basically, the extend keyword lets us add fields to an already-defined type. We can use this keyword in order to define Query fields relevant to those types in book.js and author.js. We should then also move to defining the Query resolvers for those types in the same place.</p><p>Here’s what author.js looks like with this approach:</p><pre>// author.js</pre><pre>export const typeDef = `<br>  extend type Query {<br>    author(id: Int!): Author<br>  }</pre><pre>  type Author {<br>    id: Int!<br>    firstName: String<br>    lastName: String<br>    books: [Book]<br>  }<br>`;</pre><pre>export const resolvers = {<br>  Query: {<br>    author: () =&gt; { ... },<br>  },<br>  Author: {<br>    books: () =&gt; { ... },<br>  }<br>};</pre><p>This is what book.js looks like:</p><pre>// book.js</pre><pre>export const typeDef = `<br>  extend type Query {<br>    book(id: Int!): Book<br>  }</pre><pre>  type Book {<br>    title: String<br>    author: Author<br>  }<br>`;</pre><pre>export const resolvers = {<br>  Query: {<br>    book: () =&gt; { ... },<br>  },<br>  Book: {<br>    author: () =&gt; { ... },<br>  }<br>};</pre><p>Just as before, we put it all together in schema.js:</p><pre>import { merge } from &#39;lodash&#39;;</pre><pre>import { <br>  typeDef as Author, <br>  resolvers as authorResolvers,<br>} from &#39;./author.js&#39;;</pre><pre>import { <br>  typeDef as Book, <br>  resolvers as bookResolvers,<br>} from &#39;./book.js&#39;;</pre><pre>// If you had Query fields not associated with a<br>// specific type you could put them here<br>const Query = `<br>  type Query {<br>    _empty: String<br>  }<br>`;</pre><pre>const resolvers = {};</pre><pre>makeExecutableSchema({<br>  typeDefs: [ Query, Author, Book ],<br>  resolvers: merge(resolvers, authorResolvers, bookResolvers),<br>});</pre><p>Now, the schema and resolver definitions are properly co-located with the associated types!</p><h3>Final tips</h3><p>We’ve just been through the mechanics of modularizing your server code. Here are a few additional tips that may be helpful in figuring out how to carve up your codebase:</p><ol><li>When learning, prototyping or even building a POC, putting your whole schema in a single file is likely fine: There are benefits to be able to go through your whole schema really quickly, or explain it to a coworker.</li><li>You can organize your schema and resolvers by feature: for example, putting the stuff related to the checkout system together might make sense in an ecommerce site.</li><li>Keep your resolvers in the same file as the schema definition for the fields they implement. This will allow you to reason about your code efficiently.</li><li>Wrap your SDL type definitions with a gql tag using <a href="https://github.com/apollographql/graphql-tag">graphql-tag</a>. If you’re using a GraphQL plugin for your editor or formatting your code with Prettier, you’ll be able to get syntax highlighting for SDL within your code editor as long as you prefix it with the gql tag.</li></ol><p>Now, go forth and organize your code!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F64a355%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F64a355&amp;image=https%3A%2F%2Fucarecdn.com%2F83c581fe-a404-4dd3-b60c-ad9f5cb4b6ef%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2636327dd804c0413fe8ac3f5884859/href">https://medium.com/media/e2636327dd804c0413fe8ac3f5884859/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7f71d5ed5f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/modularizing-your-graphql-schema-code-d7f71d5ed5f2">Modularizing your GraphQL schema code</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you might want a GraphQL client]]></title>
            <link>https://medium.com/apollo-stack/why-you-might-want-a-graphql-client-e864050f789c?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/e864050f789c</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ui-design]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Wed, 05 Apr 2017 17:52:54 GMT</pubDate>
            <atom:updated>2017-04-05T17:52:54.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sending requests, ensuring consistent UI, and updating the store</h4><p>If you’ve heard about GraphQL, you’ve likely also heard about GraphQL clients such as <a href="http://dev.apollodata.com/">Apollo Client</a> or <a href="https://facebook.github.io/relay/">Relay</a>. GraphQL is an API technology, so you can always access your API with a simple HTTP fetch. These client implementations offer a large number of data management features, so their core purpose can become a bit muddled. In this short post, I’ll go through why sophisticated GraphQL client clients are useful, and what they will and won’t do for you.</p><p>The best way to understand the value of something is to lose it. So, let’s first imagine a world where GraphQL clients didn’t exist and then, from that point of view, figure out what a GraphQL client implementation would have to do to be useful.</p><p><em>If you haven’t tried GraphQL or Apollo Client yet, check out the </em><a href="http://dev.apollodata.com/"><em>interactive example on our website</em></a><em>.</em></p><h4>1. Sending correctly formed requests</h4><p>Say you’re building a web application and you want to interact with a GraphQL backend. At the very basic level, all you have to do is construct POST requests with your query document, send them to the server and get a response back.</p><p>For example, you might send a JSON object like this:</p><pre>{<br>  query: &quot;query { <br>     authors {<br>       firstName<br>       lastName<br>     }<br>  }&quot;<br>}</pre><p>And receive something back from the server that looks like this:</p><pre>{<br>  data: {<br>    authors: [<br>      { firstName: &#39;Alfred&#39;, lastName: &#39;Aho&#39; },<br>      { firstName: &#39;Ravi&#39;, lastName: &#39;Sethi&#39; }    <br>    ],<br>  } <br>}</pre><p>It would be nice to have something that would just construct this JSON object, send it down to the server, wait for a result and error in a reasonable way in case something goes wrong. In addition, you’ll want this process of constructing the HTTP request and handling corresponding response to be pluggable with middlewares and afterwares, so that you can do authentication by adding an HTTP header.</p><p>Once you start adding additional features to your GraphQL implementation, like subscriptions, a simple HTTP fetch is no longer sufficient. In this case, a great network interface implementation can really help you out.</p><p>That’s what <a href="http://dev.apollodata.com/core/network.html">Network Interfaces</a> do in Apollo Client. You could use these independently of the rest of the implementation and still have something useful, and we’re hoping to make that component more independent in the future.</p><h4>2. Keeping your UI consistent across queries</h4><p>You don’t just want to fetch data; you also want to show this data to your users through a UI component. Let’s say that you have two components within your UI that each display a list of authors. So, you have two components that ask for this query to be sent to the server:</p><pre>query {<br>  authors {<br>    firstName<br>    lastName<br>  }<br>}</pre><p>Let’s call these two components UI Component #1 and UI Component #2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*0nHslOyAgJdikBPd-LR4hg.png" /><figcaption>The initial UI after we’ve loaded our authors’ names.</figcaption></figure><p>Let’s say the user clicks the “reload list” button. List #1 has to reload its list of authors’ names and display the new ones to the user. The result it now gets back looks like this:</p><pre>{<br>  data: {<br>    authors: [<br>      { firstName: &#39;Alfred&#39;, lastName: &#39;Aho&#39; },<br>      { firstName: &#39;Ravi&#39;, lastName: &#39;Sethi&#39; } ,<br>      { firstName: &#39;Jeffrey&#39;, lastName: &#39;Ullman&#39; },   <br>    ],<br>  } <br>}</pre><p>So, #1’s view will update to include this new author by the name of “Jeffrey Ullman.” But, “#2” will still be stuck in the past.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*fiBuE94ZsLRolybhwwfdww.png" /><figcaption>Disaster strikes when we hit “reload” on the first author list</figcaption></figure><p>We don’t want this to happen, because the application user might get confused about the state of the server. Is that author in there or not? Ideally, both “#1” and “#2” would update with the latest data and our UI wouldn’t fall out of sync. This is what Apollo Client’s “reactive cache” accomplishes.</p><p>The reactive cache is a collection of GraphQL query results held on the client that’s updated as the client fetches more information. We sometimes call it a “reactive” cache since it allows us to make sure that when a single piece of data is updated, every query watching that piece of data is updated as well. When you fire queries and mutations through Apollo Client, the results are written to the cache and it is used to make sure that all of the “active” queries on your page are up-to-date with each other. There are some more details as to <a href="https://dev-blog.apollodata.com/the-concepts-of-graphql-bc68bd819be3">how exactly the reactive cache works</a> but the core idea is that keeps the different parts of your UI in sync.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*xJeOLJE-Vewb45tiNfRoxw.png" /><figcaption>Happy days are here again when a GraphQL client preserves consistency</figcaption></figure><p>To learn more about how the cache works in Apollo, fire up an example app and install the <a href="https://dev-blog.apollodata.com/apollo-client-developer-tools-ff89181ebcf">Apollo Client Devtools</a>. You’ll see how the query results are decomposed into a normalized structure that allows objects to be shared across queries.</p><h4>3. Updating the cache</h4><p>Of course, in order for the reactive cache to work, we need to be able to update it with information returned from the server. In most cases, this is as easy as fetching a GraphQL query or running a mutation. When the result from the query is returned, your GraphQL client will automatically update the cache entries associated with the query. For mutations as well, if the results match up with current cache entries, they are incorporated automatically.</p><p>But, in cases where the data returned is something that includes completely new objects, for example pagination and mutation that create new items, more information is needed to specify how exactly the cache should be updated. So, we want our GraphQL client to give us a way to update the cache with new information from the server and allow us to handle these special cases. For Apollo Client, <a href="http://dev.apollodata.com/react/cache-updates.html">we’ve documented</a> these cases and how to deal with them.</p><h4>Summary</h4><p>That gives us the three core responsibilities of a GraphQL client:</p><ol><li>Allow the application developer to easily execute GraphQL queries, and configure transport-specific features like headers.</li><li>Ensure that all GraphQL results currently being displayed in an app are consistent with one another.</li><li>Provide flexible ways to update the cache with results from the server when using mutations, pagination, subscriptions, and more.</li></ol><p>The structure inherent in GraphQL makes it possible for libraries like Apollo Client to implement the above properties to make your development experience more pleasant. In particular, the most useful property of GraphQL that enables this is that GraphQL can be used both to request the data from the server and to read data from the cache for the UI components.</p><h4>Common misconceptions</h4><p>We now know that GraphQL clients are fundamentally responsible for these three requirements. Let’s dig into the details a bit and clear up some existing misconceptions around the role of client implementations.</p><ol><li><strong>Performance is the main reason to use a GraphQL client. </strong>These GraphQL clients are often referred to as “caches”. Caches are generally used to speed things up. So, many assume that the primary benefit of Apollo Client or Relay comes from the fact that it is able to improve the performance of your application by lowering roundtrips. It is certainly the case that this <em>may</em> occur: if you’re fetching data you have already requested before, Apollo Client will happily resolve it from the cache for you and save you a server roundtrip. But, this is not the primary goal of the reactive cache. The cache is meant to keep your UI consistent and predictable, and most implementations will prioritize doing that over saving your application a roundtrip to the server.</li><li><strong>Consistency between client and server. </strong>Apollo Client’s cache is currently concerned with consistency at the UI level, not at the client-server level. This means that the client will not automatically receive updates from the server in order to update your UI components. Live updates can be implemented with polling or <a href="https://github.com/apollographql/graphql-subscriptions">GraphQL subscriptions</a>. These aren’t too hard to set up, but they require the developer to opt in and do some extra work.</li></ol><h4>Spherical Cow</h4><p>Physicists sometimes use a term for a description of something that’s simplified to the point where it might only capture a very vague view of a reality: a <a href="https://en.wikipedia.org/wiki/Spherical_cow">spherical cow</a>. In this post, I’ve essentially presented such a model of Apollo Client and other GraphQL client implementations. There’s a lot of stuff it does under the hood to make your GraphQL app consistent, performant and pleasant to develop that I’ve just ignored.</p><p>But, the core responsibilities described make it clear what Apollo Client’s role is: fetch some GraphQL queries and keep them in sync with one another. Hopefully this simple mental model makes it a bit easier to navigate the maze of tools, libraries, etc. exist and get you to productivity more quickly.</p><p>If you want to learn more about concepts like this, and hear from both production GraphQL users and contributors from the Apollo community, please sign up for our free 1-day event on April 12, Apollo Day:</p><p><a href="https://www.eventbrite.com/e/apollo-day-graphql-developer-event-tickets-32267399661">Apollo Day: GraphQL Developer Event</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e864050f789c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/why-you-might-want-a-graphql-client-e864050f789c">Why you might want a GraphQL client</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persisted GraphQL Queries with Apollo Client]]></title>
            <link>https://medium.com/apollo-stack/persisted-graphql-queries-with-apollo-client-119fd7e6bba5?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/119fd7e6bba5</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Wed, 08 Feb 2017 18:44:36 GMT</pubDate>
            <atom:updated>2017-12-14T05:39:29.892Z</atom:updated>
            <content:encoded><![CDATA[<h4>Easier security and efficiency for your API</h4><blockquote>Update: This post was originally written by Dhaivat Pandya in February 2017, but we’ve updated it since them (most recently in December 2017) to include the latest information on using persisted queries with Apollo.</blockquote><p>If you’re a regular at a diner, you know that saying the full name of a dish is a rookie move. If you refer to the “double cheeseburger with bacon, fries and a coke” as a “#12”, you save yourself a bunch of words and enable the cashier to be more efficient in fulfilling your order.</p><p>There’s a popular concept in GraphQL called “persisted queries” which is the same kind of thing, but for your API. We’ve built two different tools in Apollo to make it easy to get started building with persisted queries:</p><ol><li>A<a href="https://dev-blog.apollodata.com/improve-graphql-performance-with-automatic-persisted-queries-c31d27b8e6ea">utomatic persisted queries</a> — a built-in feature when using <a href="https://github.com/apollographql/apollo-link-persisted-queries#installation">Apollo Link</a> and <a href="https://www.apollographql.com/docs/engine/">Engine</a>, works with any client or server</li><li><a href="https://github.com/apollographql/persistgraphql">persistgraphql</a> — a library to statically analyze GraphQL queries at build time, uses a tight coupling between client and server</li></ol><p>This article is going to introduce you to how persisted queries work and how you can get started using them with <a href="https://github.com/apollographql/persistgraphql">persistgraphql</a>.</p><p>If you’d like to learn more about using automatic persisted queries with the <a href="https://github.com/apollographql/apollo-link-persisted-queries#installation">Apollo Link</a> and <a href="https://www.apollographql.com/docs/engine/">Engine</a>, check out <a href="https://dev-blog.apollodata.com/improve-graphql-performance-with-automatic-persisted-queries-c31d27b8e6ea">our blog post on that instead</a>! 🎉</p><p>If you’ve built a GraphQL server in the past, you’ve probably thought about one or both of these:</p><ol><li>Restricting the queries that your server accepts by whitelisting a specific set of queries</li><li>Saving bandwidth between the client and server by only sending a query ID or hash instead of an entire GraphQL query</li></ol><p>What if we could solve the challenges of query whitelisting and bandwidth usage in one swoop? That’s what persisted queries support does! Persisted queries have been talked about a lot, <a href="https://github.com/apollostack/apollo-client/issues/1080">in Apollo Client</a>, in <a href="https://github.com/graphql/express-graphql/pull/109">express-graphql</a>, and <a href="https://www.youtube.com/watch?v=1Fg_QtzI7SU&amp;t=6s">in talks by developers at Facebook</a> and in this post, we’ll tell you everything you need to know about them: how they work, the tooling we’ve built around them and how you can incorporate persisted queries into your GraphQL application.</p><h3>What are persisted queries?</h3><p>Let’s say that we’re writing some frontend code that uses GraphQL. We might write some view layer code that looks like this:</p><pre>import COMMENT_QUERY from ‘../graphql/Comment.graphql’;</pre><pre>const withData = graphql(COMMENT_QUERY, {<br> options: ({ params }) =&gt; ({<br> …<br> }),<br> …<br>});</pre><p>where we’re using the <a href="https://dev-blog.apollodata.com/webpacking-your-graphql-documents-bf9697ed259b?source=activity---post_recommended_rollup">graphql-tag/loader</a> Webpack loader in order to import a .graphql file. When we render this component, Apollo Client will fire off the query contained within Comment.graphql. To do this, Apollo Client has to send down the query itself to the server as a string and the server will look at the query, resolve it and send back some data. All of this happens at runtime, giving rise to high bandwidth usage and unrestricted query execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*4nY38aBQi9vK-eSJPNRLeA.png" /><figcaption>Client sends down a huge query and ruins the server’s day.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*WhBPlojnj9jocgetUbjwaQ.png" /><figcaption>Adversaries can execute arbitrary GraphQL queries.</figcaption></figure><p>But <a href="https://medium.com/p/5-benefits-of-static-graphql-queries-b7fa90b0b69a">if you follow our advice</a>, you already know at build time what query the client is going to send. That is, the query document itself is in the file Comment.graphql before the client has even rendered. So the client could just tell the server “Hey, can I have the results for query number 16?” and the server, which has agreed on a number-to-query-mapping with the client, will send back the right results. We save ourselves some bandwidth by not sending down the whole document, and the server will only resolve queries that already knows about, preventing an adversary from sending malicious queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*oJGTuYheBaaiirGsKIosrQ.png" /><figcaption>Client sending a huge query is no longer a problem!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*eXAdxMmuzbmKb4bK2tO9xg.png" /><figcaption>An action shot of persisted queries bravely fighting off adversaries</figcaption></figure><p>We use the term “persisted queries” to describe this agreement of a number-to-query-mapping. What it really represents is a bidirectional mapping between GraphQL documents and generated IDs. But, in order for us to be able to implement support for persisted queries, we need to have queries that are <a href="https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a#.nhyjmg5r8"><em>statically analyzable</em></a>, meaning that we should be able to determine the query that the client sends down at buildtime. Apollo Client has adopted static queries from the start and we’ve now built the tooling needed around persisted queries to make them a drop-in addition to your app.</p><h3>How persisted queries work</h3><h4>Client</h4><p>In order to support persisted queries, we’ve built <a href="https://github.com/apollographql/persistgraphql">persistgraphql</a>, a build tool that crawls your client source code repository, pulls out GraphQL documents, creates a mapping between GraphQL documents and their generated IDs and writes that map to a JSON file. It also provides a network interface implementation for Apollo Client that takes in whole queries, but sends only the query ID to the server.</p><p>Let’s break open these pieces and see how they actually function, starting with the JSON map itself. You might imagine that the map looks something like this:</p><pre>{<br> &lt;GraphQL Document AST&gt;: &lt; ID &gt;,<br>}</pre><p>Unfortunately, keys in Javascript can only be strings or numbers. We could fix that issue by using graphql-js’s print function:</p><pre>{<br>  &lt;print(GraphQL Document AST) &gt;: &lt; ID &gt;,<br>}</pre><p>This is nearly right, but Apollo Client allows you to apply some static transformations to queries such as adding the __typename field to every level of our query. One of our queries might contain the following GraphQL document (we call this the <em>source query</em>):</p><pre>query {<br>  author {<br>    firstName<br>    lastName<br>  } <br>}</pre><p>After applying a query transformation, the query that’s actually sent to the server (we call this the <em>network query</em>) looks like this:</p><pre>query {<br>  author {<br>    firstName<br>    lastName<br>    __typename<br>  }<br>}</pre><p>Since we want to be able to implement persisted queries support within Apollo Client by simply implementing a network interface, we want our query map to be able to map between these network queries and the generated IDs. So, our final JSON map ends up looking like this:</p><pre>{<br> &lt; print(transform(GraphQL Document)) &gt;: &lt; ID &gt;,<br>}</pre><p>This means that our command line tool has to be able to apply these query transforms at build time. That’s why there’s an option you can pass to persistgraphql to apply the query transformation that adds typenames and it’s easy to add other query transformations.</p><p>Within the network interface for persisted queries, the map data structure that the persistgraphql tool outputs is made available to the client as part of the bundle. The core of this network interface consists of a single method:</p><pre>query(request: Request) {<br> // look up request.query in the map data structure<br> // find the corresponding ID<br> // send the query ID to the server, along with the query variables<br> // return a Promise for the result returned by the server<br>}</pre><p>The request.query field contains the transformed query that should be sent over the wire. The persistgraphql persisted query network interface looks up the ID associated with request.query within the map data structure. Finally, it sends this query ID is sent down to the server, along with any variables needed to evaluate the query. Simple, right?</p><h4>Server</h4><p>You can probably already guess what happens on the server. The server will receive something like this from the client:</p><pre>{<br>  id: &lt; query ID &gt;,<br>  variables: &lt; variables &gt;,<br>}</pre><p>and turn it into this:</p><pre>{<br>  query: &lt; print(GraphQL document) &gt;,<br>  variables: &lt; variables &gt;<br>}</pre><p>This means that after you drop in some really simple middleware, your server code doesn’t have to change at all since it can just pretend that it received the GraphQL document from the client, per usual.</p><h3>How to use it</h3><p>Enough talk about the internals; let’s see how to actually set up your client and server to use persisted queries. We first need to install persistgraphql:</p><pre>$ npm install --save persistgraphql</pre><p>This gives us the persistgraphql CLI tool, as well as an Apollo Client network interface. We can use this tool to create the JSON file that contains the mapping between queries and IDs. We just need to point persistgraphql to our frontend source directory that contains our .graphql files:</p><pre>$ persistgraphql ui [--add_typename]</pre><p>where we pass the --add_typename flag if we’re using the addTypename transformer within Apollo Client. If all goes well, that should produce a file called extracted_queries.json. In our client code, we have to import this file and replace our existing network interface with the PersistedQueryNetworkInterface from persistgraphql/lib/browser. This might look like this:</p><pre>import queryMap from ‘./extracted_queries.json’;<br>import { PersistedQueryNetworkInterface } from ‘persistgraphql’;</pre><pre>const networkInterface = new PersistedQueryNetworkInterface({<br>  queryMap,<br>  uri: apiUrl,<br>  opts: {<br>    credentials: ‘same-origin’,<br>    headers,<br>  },<br>});</pre><p>Notice that in order for the import statement to work correctly, you need to configure Webpack (or whatever build tool you choose to use) to handle JSON files correctly; you can check out <a href="https://github.com/apollographql/GitHunt-React">GitHunt-React</a>, our example app, for the details. Finally, on the server, we have to make a similar import (we could also use Node’s filesystem API to load the JSON file) and write a simple middleware to replace incoming query IDs with the whole thing:</p><pre>import queryMap from ‘../extracted_queries.json’;<br>import { invert } from &#39;lodash&#39;;<br>app.use(<br>  &#39;/graphql&#39;,<br>  (req, resp, next) =&gt; {<br>    if (config.persistedQueries) {<br>      const invertedMap = invert(queryMap);<br>      req.body.query = invertedMap[req.body.id];<br>    }<br>    next();<br>  },<br>);</pre><p>Of course, there are number of ways to implement the middleware. Here, we’re using invert from lodash in order to invert the map and look up by id, but you could imagine loading queries from a database or some other storage mechanism.</p><p>And, that’s it! With these changes in place, the app will start loading data using query IDs rather than entire query documents.</p><h3>Why This Matters</h3><p>Persisted queries provide a number of immediate benefits, most importantly query whitelisting and reduced bandwidth usage. Because persisted queries are static by definition, they also give you the possibility of optimizing execution on the server for specific queries, for example by hand-crafting a highly efficient database query.</p><h4>What’s next</h4><p>Persisted queries are just the first step in the direction of more production-focused features for Apollo Client. By implementing persisted queries, we’ve shown that with Apollo you can have your cake and eat it too: The features gives you great performance and security optimizations without sacrificing the <a href="https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a">fantastic developer experience</a> that Apollo is known for. As we go forward, we’ll continue to build features like persisted queries that make GraphQL a fantastic choice for prototypes and production applications alike.</p><p>If you’re interested in working on <a href="https://github.com/apollographql">Open Source GraphQL projects</a>: we’re always looking for more contributors. <a href="http://jobs.meteor.com/#5e11e6cf-5303-4c12-a3e7-11e5f8da4be1">We’re also hiring</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=119fd7e6bba5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/persisted-graphql-queries-with-apollo-client-119fd7e6bba5">Persisted GraphQL Queries with Apollo Client</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack’ing your GraphQL Documents]]></title>
            <link>https://medium.com/apollo-stack/webpacking-your-graphql-documents-bf9697ed259b?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9697ed259b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Tue, 17 Jan 2017 21:17:43 GMT</pubDate>
            <atom:updated>2017-02-06T01:40:10.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>Now you can write queries in .graphql files and use imports to load fragments</h4><p>When building a GraphQL application, there are benefits that come from placing your GraphQL query documents in their own files rather than inline with your view components. For example, you can get simpler editor and tooling support since the tools can look at static files instead of trying to parse application code. Also, it prevents you from <a href="https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a#.9okwzr2dn">accidentally manipulating queries at runtime</a>. However, until now it has been difficult to do with our GraphQL webpack loader since there was no way to have different queries share GraphQL fragments.</p><p>This is a short post that describes one of the features we recently built into our Webpack loader for GraphQL documents — <a href="https://github.com/apollostack/graphql-tag">graphql-ta</a>g — that solves this problem.</p><p>Until now, the loader only gave you the ability to load a query from a single file, but with a recent update you can now import fragment definitions from other .graphql files. This makes it easy to place GraphQL documents outside of your view component definitions and share fragments across those documents. Now that the support for these files is fully featured, you can easily take advantage of built-in editor code highlighting for .graphql files, for example on GitHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w64zULCm_M_1lXhjrDmbGg.png" /><figcaption>That sweet, sweet highlighting.</figcaption></figure><h3>Using it</h3><p>Right now, most Apollo Client apps are written by putting queries inside JavaScript template literals with a gql tag:</p><pre>export const COMMENT_QUERY = gql`<br>  query Comment($repoName: String!) {<br>    …<br>  }<br>}`;</pre><pre>const withData = graphql(COMMENT_QUERY, {<br> // options<br>});</pre><p>This is a reasonable approach. But, if we don’t want to place our queries inline with our React components, we can do that with graphql-tag/loader.To start using it, we edit the Webpack config so that it looks like this:</p><pre>module.exports = {<br>  …<br>  module: {<br>    loaders: [{<br>      test: /\.(graphql|gql)$/,<br>      exclude: /node_modules/,<br>      loader: ‘graphql-tag/loader’<br>    }]<br>   },<br>  …<br>}</pre><p>Now, we can place our query document in a file called CommentQuery.graphql, and then import it within our Javascript code:</p><pre>import COMMENT_QUERY from &#39;../graphql/CommentQuery.graphql&#39;;</pre><p>When the bundle is created, Webpack will load the .graphql file and use the GraphQL parser in order to set COMMENT_QUERY to a parsed version of the query contained within the .graphql file. Now, let’s say that this query used a fragment spread internally:</p><pre>query Comment($repoName: String!) {<br>  …<br>  ...CommentsPageComment<br>  …<br>}</pre><pre>fragment CommentsPageComment {<br>  …<br>} </pre><p>We could put both the query definition and the fragment definition in the same file. But, if the fragment is shared across multiple queries, we’d have to define it with every query that used. Instead, we can use graphql-tag/loader’s preprocessor #import statement. This is what our query file would look like:</p><pre>#import &quot;./CommentsPageComment.graphql&quot;</pre><pre>query Comment($repoName: String!) {<br> …<br> ...CommentsPageComment<br> …<br>}</pre><p>and the file CommentsPageComment.graphql would contain:</p><pre>fragment CommentsPageComment on Comment {<br>  id<br>  postedBy {<br>    login<br>    html_url<br>  }<br>  createdAt<br>  content<br>}</pre><p>This allows us to import COMMENT_QUERY as we did previously without worrying about having to import the fragment separately within our Javascript code.</p><p>That’s all you need to understand to start using graphql-tag/loader in your projects. If you’d like to see an example, you can check out how we use .graphql files and preprocessor #import statements within our example app, <a href="https://github.com/apollostack/GitHunt-React">GitHunt-React</a>.</p><h3>How it works</h3><p>The implementation of graphql-tag/loader is incredibly simple. Since it is a Webpack loader, it has to turn each .graphql into a bit of Javascript code that Webpack can place into the bundle it creates. Let’s consider what happens when we try to import this file:</p><pre>#import &quot;./CommentsPageComment.graphql&quot;</pre><pre>query Comment($repoName: String!) {<br> …<br> ...CommentsPageComment<br> …<br>}</pre><p>Notice that the first line is a GraphQL comment. This means that to an ordinary GraphQL parser, the import statement would be ignored entirely. But, graphql-tag/loader will process it and replace it with a require statement in the outputted code. It will then parse the whole document contained in this file and combine it with the definitions in the imported file. The Javascript code that graphql-tag/loader outputs should look like this:</p><pre>var doc = // JSON object that represents the parsed GraphQL document<br>doc.definitions = doc.definitions<br>  .concat(<br>    require(&#39;CommentsPageComment.graphql&#39;).definitions<br>  );<br>module.exports = doc;</pre><p>Notice that with the require statement, graphql-tag/loader will be executed again on CommentsPageComment.graphql by Webpack. This makes it possible to have #import statements within that file too. By generating this Javascript code, the loader makes it possible to import your .graphql files from your Javascript code.</p><h3>Next steps</h3><p>Importing files that contain static queries makes it possible to <a href="https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a#.tu5h811jv">build all kinds of neat tools</a>, including support for persisted queries. We’ve actually built support for persisted queries on top of this improved Webpack loader, and we’ll have a blog post explaining how to use them soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9697ed259b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/webpacking-your-graphql-documents-bf9697ed259b">Webpack’ing your GraphQL Documents</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL Concepts Visualized]]></title>
            <link>https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc68bd819be3</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Thu, 18 Aug 2016 18:20:48 GMT</pubDate>
            <atom:updated>2018-04-06T09:31:01.043Z</atom:updated>
            <content:encoded><![CDATA[<h4>Our mental model of GraphQL, explained in diagrams</h4><p>GraphQL is often explained as a “unified interface to access data from different sources”. Although this explanation is accurate, it doesn’t reveal the underlying ideas or the motivation behind GraphQL, or even why it is called “GraphQL” — you can see the stars and the night, but not quite the “The Starry Night”.</p><p>The true heart of GraphQL lies in what I think of as the application data graph. In this article, I’ll introduce the app data graph, talk about how GraphQL queries operate on the app data graph and how we can cache GraphQL query results by exploiting their tree structure.</p><p><em>Update 2/7/2017: You can now see this in talk form below!</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzWhVAN4Tg6M%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzWhVAN4Tg6M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzWhVAN4Tg6M%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2d66b92a3d57059f0eef317ee302a18/href">https://medium.com/media/b2d66b92a3d57059f0eef317ee302a18/href</a></iframe><h3><strong>The application data graph</strong></h3><p>A lot of data in modern applications can be represented using a graph of nodes and edges, with nodes representing objects and the edges representing relationships between these objects.</p><p>For instance, say we’re building a cataloging system for libraries. To keep it simple, our catalog has a bunch of books and authors and each of these books has at least one author. The authors also have coauthors with whom the author has written at least one book.</p><p>If we visualize these relationships in the form of a graph, they look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*EmhOknzZEu9Q6U3q5NmT9Q.png" /></figure><p>The graph represents the relationships between the various pieces of data that we have and the entities (e.g. “Book” and “Author”) we’re trying to represent. Pretty much all applications operate on this kind of graph: they read from it and write to it. This is where GraphQL comes in.</p><blockquote><strong>GraphQL allows us to extract trees from the app data graph.</strong></blockquote><p>That sounds pretty puzzling at first, but let’s break down what it means. Fundamentally, a tree is a graph which has a starting point (the root) and the property that you can’t trace your finger along the nodes through the edges and come back to the same node, i.e. it has no cycles.</p><h4>Traversing the Graph with GraphQL</h4><p>Let’s take a look at an example of a GraphQL query and how it “extracts a tree” out of an application graph. Here’s a query we could run against the data graph we were just talking about:</p><pre>query {<br>  book(isbn: &quot;9780674430006&quot;) {<br>    title <br>    authors {<br>      name<br>    }<br>  }<br>}</pre><p>Once the server resolves the query, it returns this query result:</p><pre>{<br>  book: {<br>    title: “Capital in the Twenty First Century”,<br>    authors: [<br>      { name: ‘Thomas Piketty’ },<br>      { name: ‘Arthur Goldhammer’ },<br>    ]<br>  }<br>}</pre><p>Here’s what that looks like in terms of the application data graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*9ZFclOcI4mvp4j4bymi8cQ.png" /></figure><h4>Query Paths</h4><p>Let’s figure out how this information was actually extracted from the graph by the GraphQL query.</p><p>GraphQL allows us to define a <em>Root Query Type</em> (we’ll refer to it as <em>RootQuery</em>), which defines where a GraphQL query can start when traversing the app data graph. In our example, we start with a “Book” node, which we’ve selected using its ISBN number with the query field <em>“book(isbn: …)”</em>. Then, the GraphQL query traverses the graph by following the edges marked by each of the nested fields. For our query, it hops from the “Book” node to the node containing the string title of the book through the “<em>title” </em>field in the query<em>. </em>It also gets “Author” nodes by following the edges on the “Book” that are labelled with the <em>“authors” </em>field and gets each author’s “<em>name</em>” as well.</p><p>To see how this result creates a tree, we just have to move around the nodes to make it look more like one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*ze1LAOQN-4sQJQ4p3mdkNw.png" /></figure><p>For each piece of information that the query returns, there’s an associated query path, which consists of the fields in the GraphQL query that we followed to get to that information. For example, the book’s title “Capital” has the following <em>query path</em>:</p><blockquote>RootQuery → book(isbn: “9780674430006”) → title</blockquote><p>The fields in our GraphQL query (i.e. <em>book</em>, <em>authors</em>, <em>name</em>) specify which edges should be followed in the application data graph to get our desired result. This is where GraphQL gets its name: <strong>GraphQL is a query language that traverses your data graph to produce a query result tree.</strong></p><h3>Caching GraphQL results</h3><p>To build a really snappy, fluid application that doesn’t spend most of its life presenting a loading spinner to its users, we want to reduce roundtrips to the server by using a cache. <strong>It turns out that the tree structure of GraphQL lends itself extremely well to client-side caching.</strong></p><p>As a simple example, suppose we have some code on your page that fetches the following GraphQL query:</p><pre>query {<br>  author(id: &quot;8&quot;) {<br>    name<br>  }<br>}</pre><p>Later on, some other section of the page requests the same query again. Unless we absolutely need the newest data, this second query can be resolved with the data we already have! This means that the cache needs to be able to resolve queries without ever sending them to the server, making our application faster. But we can do much better than just caching the exact queries we have previously fetched.</p><p>Let’s take a look at the approach Apollo Client takes to caching GraphQL results. Fundamentally, GraphQL query results are trees of information from your server-side data graph. We want to be able to cache these result trees to avoid reloading them every time we need them again. To do this, we make a key assumption:</p><p>Apollo Client assumes that each path within your application data graph, as specified by your GraphQL queries, points to a stable piece of information.</p><p>If this doesn’t hold true in some cases (e.g. when the information pointed to by a particular query path changes really frequently), we can prevent Apollo Client from making this assumption with the concept of <em>object identifiers</em>, which we’ll introduce later. But, in general, this turns out to be a reasonable assumption to make when it comes to caching.</p><h4>Same path, same object</h4><p>The assumption of “same path means same object” introduced by the last point is incredibly useful. For example, say we have these two queries, fired one after the other:</p><pre>query particularAuthor {<br>  author(name: &quot;Thomas Piketty&quot;) {<br>    name<br>    age<br>  }<br>}</pre><pre>query authorAndBook {<br>  book(isbn: &quot;9780674430006&quot;) {<br>    title<br>  }</pre><pre>  author(name: &quot;Thomas Piketty&quot;) {<br>    name<br>    age<br>  }<br>}</pre><p>You can see just by looking at the queries that the second query doesn’t need to go to the server to get the name of the author. This information can just be found within the cache from the result of the previous query.</p><p>Apollo Client uses this kind of logic to remove parts of the query based on the data already in the cache. It’s able to do this kind of diffing because of the path assumption. It assumes that the path <em>RootQuery</em>→<em>author(id: 6)</em>→<em>name </em>would have fetched the same information in both queries. Of course, if this assumption doesn’t work for you, you can override caching entirely by using the <em>forceFetch</em> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*jiLMWVM17NQWMwt0nbF3TA.gif" /></figure><p>This assumption works really well because the query path also includes the arguments we use within GraphQL. For example…</p><blockquote>RootQuery → author(id: 3) → name</blockquote><p>is different from</p><blockquote>RootQuery → author(id: 6) → name</blockquote><p>…so Apollo Client won’t assume that they represent the same information and try to merge one with the result of the other.</p><h4>Use <em>object identifiers </em>when the path assumption isn’t enough</h4><p>It turns out that we can do even better than just following query paths from the root. Sometimes, you might access the same object through two totally different queries, giving that object two different query paths.</p><p>For example, given that each of our authors has some set of coauthors, we can end up accessing some “Author” objects through that field:</p><pre>query {<br>  author(name: &quot;Arthur Goldhammer&quot;) {<br>    coauthors {<br>      name<br>      id<br>    }<br>  } <br>}</pre><p>But we can also access an author directly from the root:</p><pre>query {<br>  author(id: &quot;5&quot;) {<br>    name<br>    id<br>  }<br>}</pre><p>Assume that the author with the name of “Arthur Goldhammer” and the author of ID 5 are coauthors on some book. Then, we’d end up saving the same information (i.e. the information about Thomas Piketty, the author with ID 5) twice in our cache.</p><p>This is that would would like in our tree cache structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*jnl1KkctOna3AuIJ9MNz5w.png" /></figure><p>The problem is that both queries are referring to the same piece of information within the app data graph, but Apollo Client has no way to know that yet. To solve that issue, Apollo Client supports a second concept: object identifiers. Basically, you can specify a unique identifier for any object you query. Then, <strong>Apollo Client assumes that all objects with the same object identifier represent the same piece of information</strong>.</p><p>Once Apollo Client knows that, it can rearrange the cache in a much nicer way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBhiGFzFQ3TetvQ6W760Rw.gif" /></figure><p>This means that object identifiers have to be unique across your whole app. As a consequence, you can’t just use your SQL IDs directly, because then you might have an author with a SQL ID of 5 and a book with a SQL ID of 5. But this is easy to fix: to generate a unique object identifier, just append the <em>__typename </em>returned by GraphQL to the IDs generated by your backend. So, an author with a SQL ID of <em>5</em> could have an object identifier of <em>Author:5</em> or something similar.</p><h3>Keeping query results consistent</h3><p>Continuing on with the last two queries we just dealt with, let’s think about what happens if some data changes. For example, what if you fetch some other query and realize that the author with an ID of 5 has changed his/her name? What happens to the parts of your UI that currently refer to the old name that the author with an ID of 5 had?</p><p>Here’s the awesome part: they will get updated automatically. That leads us to one more guarantee that Apollo Client provides: <strong>If any of a watched query tree’s nodes change in value, the query will be updated with the new result</strong>.</p><p>So, in this case, we have two queries that both rely on the author with an object identifier of “Author:5”. Since both query trees refer to this author, any update to the author’s information will be propagated to both queries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4bBth-5yjEejx4AN1RFUw.gif" /></figure><p>If you use a view integration like <em>react-apollo</em> or <em>angular2-apollo</em> with Apollo Client, you don’t have to worry about setting this up: your components will just get the new data handed to them and re-render automatically. If you’re not using a view integration, the core method <em>watchQuery</em> does the same thing by giving you an observable that is updated whenever the store changes.</p><p>Sometimes it doesn’t make sense for your application to have object identifiers for everything, or you might not want to deal with them directly in your code but still need particular bits of information in the cache to be updated. This is why we expose convenient but powerful APIs such as <em>updateQueries </em>or <em>fetchMore </em>that let you incorporate new information into these query trees with very granular control.</p><h3>Summary</h3><p>The backbone of any application lies in the app data graph. Back in the day, when we had to roll our own HTTP requests to REST endpoints to get stuff into and out of this application graph, caching on the client was incredibly hard because data fetching was very application-specific. GraphQL, on the other hand, gives us lots of information we can use to automatically cache stuff.</p><p>If you understand five simple concepts, you can understand how reactivity and caching (i.e. all the magic that makes your app fast and slick) work within Apollo Client. Here they are, restated:</p><ol><li>GraphQL queries represent a way to get trees out of your app data graph. We call these <em>query result trees.</em></li><li>Apollo Client caches <em>query result trees</em>. To do this, it applies two assumptions:</li><li><em>Same path, same object </em>— the same query path usually leads to the same piece of information.</li><li><em>Object identifiers when the path is not enough</em> — if two results are given the same object identifier, they represent the same node/piece of information.</li><li>If any cache node involved in a query result tree is updated, Apollo Client will update the query with a new result.</li></ol><p>The above is all you need to know to be an expert in Apollo Client and GraphQL caching in general. Too much for one post? Don’t worry — we’ll keep posting more conceptual information like this when possible, so that everyone can understand the purpose behind GraphQL, where it gets its name, and how to reason clearly about any aspect of GraphQL result caching.</p><p><em>Thanks to </em><a href="https://medium.com/u/68ec6b2d4f30"><em>Slava Kim</em></a><em> for the awesome diagrams and feedback on this post!</em></p><figure><a href="https://www.apollographql.com/engine?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=engine-feat-201804"><img alt="" src="https://cdn-images-1.medium.com/max/950/1*zHlANoouusZ92unyBjkL5A.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc68bd819be3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3">GraphQL Concepts Visualized</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snappier UIs with Apollo Client + GraphQL]]></title>
            <link>https://medium.com/apollo-stack/snappier-uis-with-apollo-client-graphql-bffab0b52b79?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/bffab0b52b79</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Thu, 21 Jul 2016 17:17:50 GMT</pubDate>
            <atom:updated>2016-09-15T18:34:11.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>We started using Apollo Client in production in Meteor Galaxy, and gained insights from it to make Apollo Client faster.</h4><p>We <a href="https://www.youtube.com/watch?v=xwz1aXkJLLA">recently reimplemented</a> parts of the UI for <a href="https://www.meteor.com/hosting">Meteor Galaxy</a> using Apollo Client and GraphQL. This gives us a great platform to experiment with performance improvements within Apollo Client and see immediate impact.</p><p>Now that the world considers Javascript a Real Language™ and web applications Real Software™, there is some great performance tooling for Javascript. Armed with the Chrome CPU profiler and the network requests tab, I set out to see how we could improve Apollo Client performance. As the first batch of work, we discovered and eliminated no-op re-renders and implemented a simple scheduling system for polling queries that relies on <a href="https://medium.com/apollo-stack/query-batching-in-apollo-63acfd859862">Apollo’s query batching</a> to reduce server roundtrips.</p><h3>Reducing React re-renders</h3><p>The Galaxy UI uses React as the view layer. Here’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bml88jBHUiboztgMh8Fdmw.png" /></figure><p>There are many components being rendered on this page but only a few important ones. We have the app list component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rP3GOY4EKlwCHDT7WBAffw.png" /><figcaption>App list</figcaption></figure><p>And the user activity feed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*hO5VujFAPNb7TlVNRKE0yA.png" /><figcaption>User activity feed</figcaption></figure><p>Each of these components have their own GraphQL query attached via <a href="http://docs.apollostack.com/apollo-client/react.html">react-apollo</a>, and update periodically using the <em>pollInterval</em> option provided by Apollo Client. It turns out that the app list gets new information pretty frequently, whereas the information within the activity feed stays relatively stable.</p><p>While looking at the Chrome profiler to investigate performance, we noticed that the user activity feed component was re-rendered on each result from a polling query even if there were no changes in the data. We hypothesized we could eliminate these useless re-renders if we could prevent query observers getting notified unless the query result had actually changed.</p><p>It isn’t immediately clear if this helps performance. React first renders components to a virtual DOM, diffs this against the real DOM and then only applies the updates to the real DOM. So, if we were to do a deep comparison of data in order to prevent a React render, we might not end up with a significant improvement in performance since we might replace the virtual DOM diffing with a different type of deep comparison. On the other hand, the DOM representation of a data object is probably significantly more complicated than the data object itself so it is reasonable to expect some performance improvement.</p><p>Fortunately, the data spoke for itself. With the Chrome CPU profiler, we measured CPU usage in the Galaxy UI before the deep data comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*HpvT2RnWmsFIIGAIktDvAQ.png" /><figcaption>Before</figcaption></figure><p>As you can see, there are multiple React renders for our two primary components and the update for all of the items takes about 80 ms to render. With deep data comparison, we had a different story:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Nl7-FuXm7N8XO902mB7hbw.png" /><figcaption>After</figcaption></figure><p>We eliminated the rendering of the user activity feed and also reduced rendering time for the container items to about 40 ms since not all of the container had to re-render. This is a pretty simple page with only a couple of polling queries. A more complicated component tree with more queries would see even more significant performance improvements.</p><h3>Polling query alignment</h3><p>The app list and the user activity feed are also involved in another performance feature we added to Apollo Client.</p><p>If you switch tabs in Galaxy UI and then switch back to the container list tab, the app list polling query will be stopped and then started again. This means that the user activity feed polling query and the app list polling query can get pretty badly out of sync. This what that looks like in Chrome Dev Tools network tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Qa2vR2c0S7ExmRPYS7P8A.png" /><figcaption>Out of sync polling queries</figcaption></figure><p>These queries run on the same interval (5 seconds) but still fire separately with a chunk of time in between. This means that they can’t be batched together automatically with the <a href="https://medium.com/apollo-stack/query-batching-in-apollo-63acfd859862">Apollo query batching feature</a>. There are number of complicated things we could do to solve this problem. For example, we could ask app developers to pick polling intervals that are multiples of one another and attempt to align the intervals.</p><p>But, there’s a much simpler solution that will improve performance most of the time. Most polling queries that we have any hope of batching together probably run on the same time interval in most applications. Given this hunch, it makes sense to just fire all the queries on the same polling interval at the same time. This means that they’ll be placed in the same tick of the batcher and will be dealt with in a single server roundtrip.</p><p>Here’s what that it looks like in the network tab after we implemented polling interval alignment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ez4Yofc7v0z1Au6y_t9W_g.png" /><figcaption>In sync polling queries</figcaption></figure><p>You can’t tell from this picture, but each of these requests now consists of two GraphQL queries batched together. So, with this simple change, all the queries on a page that operate on the same interval will fire in a single server roundtrip. We didn’t have to change any of the application code: Apollo Client just made it work.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fxwz1aXkJLLA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dxwz1aXkJLLA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fxwz1aXkJLLA%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac7c2aaed453a2ae87b029711d62d35/href">https://medium.com/media/1ac7c2aaed453a2ae87b029711d62d35/href</a></iframe><h3>Next Steps</h3><p>Both of these features are now available starting with version 0.4.6 of Apollo Client. This means you just need an <em>npm update</em> to eliminate no-op UI re-renders and reduce roundtrips to your server.</p><p>We’re now looking at improving GraphQL server side performance with data collected from <a href="http://www.apollostack.com/optics">Apollo Optics</a> and we’ll post about what we find. If this and other GraphQL-related stuff sounds cool, follow us on Medium!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bffab0b52b79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/snappier-uis-with-apollo-client-graphql-bffab0b52b79">Snappier UIs with Apollo Client + GraphQL</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Query batching in Apollo]]></title>
            <link>https://medium.com/apollo-stack/query-batching-in-apollo-63acfd859862?source=rss-c066cfeacf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/63acfd859862</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dhaivat Pandya]]></dc:creator>
            <pubDate>Wed, 29 Jun 2016 18:30:49 GMT</pubDate>
            <atom:updated>2016-09-21T00:27:53.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>TL;DR: Pass one new option to Apollo Client to turn on automatic query batching, without changing your server or UI code at all.</h4><p>You don’t need anything fancy to load some data from a GraphQL server. All you need for a basic client is a POST request that sends a query down to the server and gets a result back. However, GraphQL queries include a lot of useful information that can be used to make your application faster and more efficient. This is why we have smart client implementations, such as Apollo Client and Relay, that take advantage of GraphQL’s query structure to do useful things.</p><p>Smart GraphQL clients can make interaction with the server more efficient by reducing the number of roundtrips to fetch data. A common way to reduce server roundtrips is through caching, because the fastest way to load something is to already have it. But it turns out that caching isn’t the only thing that can make server communication more efficient.</p><h4>What is query batching?</h4><p>GraphQL query batching means sending multiple queries to the server in one request, which can have some pretty significant benefits:</p><ol><li>Reducing the total number of server roundtrips, which can incur significant overhead in HTTP 1.x.</li><li>When queries are sent in one request, you can use <a href="https://github.com/facebook/dataloader">DataLoader</a> to batch loading the actual data from your backend API or database.</li></ol><p>When you load your UI on the client, it might fire several queries in a short period of time to put together its initial state. One simple strategy to improve this without changing any of the UI code is to batch together requests made within a small time interval. This way, all of the data can be loaded in one roundtrip, without any extra effort.</p><p>While <a href="https://www.youtube.com/watch?v=xwz1aXkJLLA">updating the UI for Meteor Galaxy to use Apollo Client</a>, we realized how desirable it is to have query batching in a production app. So, we implemented automatic query batching in Apollo Client.</p><p>In this post, we’ll first take a look at how we can use batching and then we’ll open up the box and see how it is implemented. We’ll also consider some next steps we can take to make batching even more awesome in GraphQL.</p><h3>Using batching</h3><p>We wanted ensure that an application developer using Apollo Client wouldn’t have to do anything extra to get batching to happen; you should get it “for free”. For example, say you have two UI components that each fire off a couple of GraphQL queries with Apollo Client:</p><pre>// these queries may be loaded from two different places within your<br>// code.</pre><pre>client.query({ query: query1 })<br>client.query({ query: query2 })</pre><p>Batching is turned off in Apollo Client by default. To turn it on, all you have to do is set the <em>shouldBatch</em> option in the constructor:</p><pre>const client = new ApolloClient({<br> // ... other options ...<br> shouldBatch: true,<br>});</pre><p>And that’s it! Now the two queries above will be sent in one request.</p><h4>Batching using time intervals</h4><p>The query batcher operates on “ticks” — it checks a queue every 10 milliseconds to see if there are any pending queries. If there are multiple queries in the queue, they are combined into one server request. So, as long as the two queries above are fired within the same 10-millisecond tick of the batcher, they’ll be sent as one request, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*STFomheClBDuyNolDUIWWw.png" /><figcaption>Query batcher queue</figcaption></figure><p>Notice that your application code can remain completely oblivious to this batching. Other than providing an additional option to the <em>ApolloClient </em>constructor, you don’t have to change anything else about your application to start getting the benefits of batching. <a href="http://docs.apollostack.com/apollo-client/network.html#query-batching">Check out the docs</a> for a slightly closer look at the semantics of batching and how you can use it with custom network interface implementations.</p><h3>A look inside</h3><p>Let’s take a look at how this works. Here’s how the pieces fit together at a high level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*yDls-FaZwIAw-tFJ2-xboA.png" /><figcaption>Batching architecture</figcaption></figure><p>Let’s consider a case where we fetch two queries, one after another. Both of the queries will go through the <em>QueryManager</em> and will be placed into the <em>QueryBatcher</em>’s queue. Then, during the next tick of the <em>QueryBatcher</em>, these queries will be placed into an array and passed along to an instance of the <em>BatchedNetworkInterface</em>. Once the results for both of the queries have returned from the server, the <em>QueryBatcher </em>will resolve the promises issued for both of the queries.</p><p>The important bit here isn’t actually the <em>QueryBatcher</em>: that just acts as a consumer on a queue. Rather, it is the implementation of a <em>BatchedNetworkInterface</em> that batches together multiple requests in a way that works with any spec-compliant GraphQL server.</p><h3>Batching with no special server support</h3><p>All GraphQL servers expose a way for us to submit a single query and receive a single result in return. However, there is little support to submit multiple queries and receive results for each of them in a single roundtrip. So, we need to utilize a method that can turn multiple queries into a single query, submit it to the server, receive a single result and then unpack it into results for each of the queries initially submitted. This is all stuff that the default network interface in Apollo Client does for you.</p><p>It does this by using a pretty simple concept called <em>query merging</em>. It involves taking multiple queries and putting them all under a single root query. As a simple example, say we’re telling the <em>BatchedNetworkInterface</em> to batch these two queries:</p><pre>query firstQuery {<br>   author {<br>    firstName<br>    lastName<br>  }<br>}</pre><pre>query secondQuery {<br>  fortuneCookie<br>}</pre><p>Then, we can imagine a simple approach to merging that produces the following query:</p><pre>query ___composed {<br>  author {<br>    firstName<br>    lastName<br>  }</pre><pre>  fortuneCookie<br>}</pre><p>However, the devil is in the details. We’ve picked nice, non-conflicting names in our two example queries, but we have no guarantee of that being the case when we are attempting to merge arbitrary queries. So, we turn to a nice feature of GraphQL: aliasing. Basically, this allows us to refer to a field with a different name and the server will use this name when returning the result. For example, given the following query:</p><pre><br>query ___composed {<br>  aliasName: author {<br>    firstName<br>    lastName<br>  }<br>}</pre><p>The server will return a result that looks like the following:</p><pre>{<br>  “aliasName”: {<br>    “firstName”: “John”,<br>    “lastName”: “Smith”<br>  }<br>}</pre><p>Using this feature of GraphQL, we can step through the AST of a query and rename all of the top-level fields, inline fragments and named fragments in a way that makes sure that they will never conflict once merged. We also rename variables since two queries can definitely refer to a variable that takes on different values in each query (e.g. a variable like <em>id)</em>. When we apply this query merging to the queries we just mentioned, we get the following composed query:</p><pre>query ___composed {<br>  ___firstQuery___requestIndex_0___fieldIndex_0: author {<br>    firstName<br>    lastName<br>  }</pre><pre>  ___secondQuery___requestIndex_1___fieldIndex_0: fortuneCookie<br>}</pre><p>This query is then sent down to the server and we get a result that looks like this:</p><pre><br>{<br> “___firstQuery___requestIndex_0___fieldIndex_0”: {<br>   “firstName”: “John”,<br>   “lastName”: “Smith”<br> },</pre><pre> “___secondQuery___requestIndex_1___fieldIndex_0”: “No snowflake in an avalanche ever feels responsible”,<br>}</pre><p>This does look a bit ugly, but your frontend code will never see any of this. The network interface will automatically unpack this result into the results you’d expect for the queries you originally submitted:</p><pre><br>{<br>  “author”: {<br>    “firstName”: “John”,<br>    “lastName”: “Smith”<br>  }<br>}</pre><pre>{<br>  “fortuneCookie”: “No snowflake in an avalanche ever feels responsible”<br>}<br></pre><p>The aliasing allows us to establish a one-to-one relationship between the fields returned by the server and the fields in the query originally submitted, allowing the network interface to unpack the result correctly.</p><p>This style of query merging can work with <em>any </em>GraphQL server since it only uses what is available in the GraphQL specification. The merged queries aren’t the prettiest, but Apollo Client handles this for you and allows your UI to render with a single roundtrip.</p><h3>Transport-level batching</h3><p>Although query merging is very effective, it has a few downsides. Primarily, if you’re trying to debug stuff from the server’s point of view, you’ll see queries that look very different from what you initially fired on the client, which could make it harder to debug your queries. One potential solution is described by Lee Byron, one of the creators of GraphQL, <a href="https://medium.com/apollo-stack/new-features-in-graphql-batch-defer-stream-live-and-subscribe-7585d0c28b07#.7amluhe5g">in his talk about new GraphQL features</a>: batching at the network transport level.</p><p>In most current GraphQL servers, requests are sent in the following form:</p><pre>{<br>  &quot;query&quot;: “&lt; query string goes here &gt;”,<br>  &quot;variables&quot;: {<br>    &lt;variable values go here&gt;<br>  }<br>}</pre><p>The GraphQL server then resolves the query string and returns a single result.</p><p>Instead, imagine we submitted a request that looked like this:</p><pre>[<br>  {<br>    query: &lt; query 0 &gt;,<br>    variables: &lt; variables for query 0 &gt;,<br>  },<br>  {<br>    query: &lt; query 1 &gt;,<br>    variables: &lt; variables for query 1 &gt;,<br>  },<br>  {<br>    query: &lt; query n &gt;<br>    variables: &lt; variables for query n &gt;,<br>  }<br>]</pre><p>And the server would return a response that looks like:</p><pre>[<br>  &lt;result for query 0&gt;,<br>  &lt;result for query 1&gt;,<br>  ...<br>  &lt;result for query n&gt;<br>]</pre><p>This is another way of accomplishing what we are currently doing with query merging: fetching the results for multiple queries in a single roundtrip. However, this is much better, since the queries you see on the server will look <em>exactly </em>as they do on the client.</p><p>Transport-level batching is easier to debug than query merging, but it requires additional server support. The server has to know how to process an array of queries and respond with an array of results. We will soon be implementing support for this in <a href="https://github.com/apollostack/apollo-server">Apollo Server</a>, and hopefully the GraphQL community can work together to come up with a standard approach that can be used with all GraphQL server implementations.</p><p>In the meantime, just passing an additional option to the Apollo Client constructor will let you load your UI in a single roundtrip rather than a dozen, without needing to put in any effort to manually merge queries using fragments. Then, once transport-level batching is built into most GraphQL servers, you’ll be able to reap these benefits while still getting nice-looking queries in your server logs.</p><p>Want to try this out? <a href="http://docs.apollostack.com/apollo-client/index.html">Check out Apollo Client.</a> And follow us on Medium for more GraphQL and Apollo content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63acfd859862" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apollo-stack/query-batching-in-apollo-63acfd859862">Query batching in Apollo</a> was originally published in <a href="https://medium.com/apollo-stack">Apollo GraphQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>