<?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[Naresh Bhatia - Medium]]></title>
        <description><![CDATA[Thoughts on front-end development. - Medium]]></description>
        <link>https://medium.com/naresh-bhatia?source=rss----4814260e8609---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Naresh Bhatia - Medium</title>
            <link>https://medium.com/naresh-bhatia?source=rss----4814260e8609---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:49:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/naresh-bhatia" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GraphQL concepts I wish someone explained to me a year ago [Series Update 2/2]]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-series-update-2-2-b246b4e64c5e?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/b246b4e64c5e</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 02:20:14 GMT</pubDate>
            <atom:updated>2019-01-07T02:20:14.116Z</atom:updated>
            <content:encoded><![CDATA[<p>Happy new year everyone! We’re already in 2019 and I’m excited by all of you looking to learn GraphQL this year. Now that I finished writing this series, I thought I’d check in with you–have any questions or comments?</p><p>Before we close the books on this one, let’s take a quick recap of the last few parts I published…</p><h3>Finishing implementing mutations and adding subscriptions</h3><p>In part 5, we implemented mutations on our client to help us in our whimsical mission–creating some authors and publishing books out of thin air for our bookstore example.</p><p>From there, we started with the real fun stuff in parts 6 and 7–subscriptions. We used them to display changes to our bookstore in real time. On the server, we replaced Apollo PubSub, because the default implementation doesn’t scale. There are more robust implementations, however, many are not documented well.</p><p>We ended up creating a pub/sub mechanism using Redis to distribute published messages over multiple servers. Here’s the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CR3KoXhXsIWxvBjO4uXKEg.jpeg" /></figure><p>Lastly, we implemented matching subscriptions on our client to close the loop. With this, you should feel empowered to write your own GraphQL applications from scratch.</p><h3>Miss any parts or want a refresher?</h3><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><h3>If you’re already caught up to this point…</h3><p>And if you found this series helpful, please share it with your fellow developers.</p><p>Until then, happy computing!</p><p>-Naresh</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b246b4e64c5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-series-update-2-2-b246b4e64c5e">GraphQL concepts I wish someone explained to me a year ago [Series Update 2/2]</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/3b84203fb0b9</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 02:37:10 GMT</pubDate>
            <atom:updated>2019-01-13T02:51:20.046Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 7: Subscriptions (client implementation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2E5-VeVbYLlREDUfmWEG5Q.png" /><figcaption>Image based on <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a>’s pen</figcaption></figure><p><em>In part 6 of this series we implemented subscriptions on the Bookstore server. In this last and final part, we jump back to the client and implement matching subscriptions there.</em></p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><strong>Part 7: Subscriptions (client implementation)</strong></li></ul><h3>Source Code</h3><p>You can download the code for this part by executing the following commands. Skip the first command if you have already cloned the repository.</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout master</pre><h3>Test Drive</h3><p>Before diving into the implementation, let’s look at how the final implementation works. Make sure you have <a href="https://yarnpkg.com/">yarn</a> installed on your machine. Now execute the following commands:</p><pre>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><p>This starts the server. In a different shell, execute the following commands to start the client:</p><pre>cd apollo-bookstore-client<br>yarn<br>yarn start</pre><p>Point your browser to <a href="http://localhost:3000/">http://localhost:3000/</a>. You should see the familiar GraphQL Bookstore client. To prove that subscriptions are working, open another instance of the client in a new browser window. Do some mutations in one window. You will see that both windows show the results of the mutation simultaneously. Really cool, isn’t it?</p><h3>Subscription Implementation</h3><h4>Download schema and run codegen</h4><p>Since the schema on the server has changed, we need to run the gql:schema script again. Also, as we add subscriptions in the client, we need to run the gql:types script to generate new TypeScript type definitions.</p><h4>Add subscriptions to containers</h4><p>We will add subscriptions to our container components. Recall, container components are responsible for fetching data from the server and handing it to the panels. Whenever the server sends us a subscription event, we will update the Apollo cache with the mutated entity. This will trigger a refresh of the component, displaying the changes.</p><p>Let’s use the authorMutated event as an example. We declare the subscription at the end of authors-container.tsx:</p><pre><strong>const </strong>AUTHOR_MUTATED = gql`<br>    subscription AuthorMutated {<br>        authorMutated {<br>            mutation<br>            node {<br>                __typename<br>                id<br>                name<br>            }<br>        }<br>    }<br>`;</pre><p>We’ll now modify the AuthorsContainer to subscribe to this event. This is a bit involved, so let’s take it one step at a time. Here’s the modified AuthorsContainer:</p><pre><strong>export class </strong>AuthorsContainer <strong>extends </strong>React.Component {<br>    unsubscribe = <strong>null</strong>;<br><br>    render() {<br>        <strong>return </strong>(<br>            &lt;DefaultQuery query={GET_AUTHORS}&gt;<br>                {({ data, subscribeToMore }) =&gt; {<br>                    // Subscribe to author mutations - only once<br>                    <strong>if </strong>(!<strong>this</strong>.unsubscribe) {<br>                        <strong>this</strong>.unsubscribe =<br>                            subscribeToAuthorMutations(<br>                                subscribeToMore<br>                            );<br>                    }<br><br>                    <strong>return </strong>&lt;AuthorsPanel data={data} /&gt;;<br>                }}<br>            &lt;/DefaultQuery&gt;<br>        );<br>    }<br><br>    componentWillUnmount() {<br>        <strong>if </strong>(<strong>this</strong>.unsubscribe) {<br>            <strong>this</strong>.unsubscribe();<br>        }<br>    }<br>}</pre><p>Note that we are subscribing to the authorMutated event in the render method by calling subscribeToAuthorMutations(). However, we should subscribe to this event only once during the lifetime of the component. Hence we retain the unsubscribe function returned by the subscribe method in a class property called unsubscribe. We also check for the presence of this function — if it is already present, we know that we’re already subscribed and we avoid subscribing again.</p><p>Now let’s look at the subscribeToAuthorMutations() function. This function takes subscribeToMore as a parameter. Note that subscribeToMore has been passed to us as an argument of the render prop method above — it is a function that sets up a subscription and returns a function that you can use to unsubscribe. You can read more about subscribeToMore <a href="https://www.apollographql.com/docs/react/essentials/queries.html#render-prop">here</a>. We are simply passing it down.</p><pre><strong>function </strong>subscribeToAuthorMutations(subscribeToMore) {<br>    <strong>return </strong>subscribeToMore({<br>        document: AUTHOR_MUTATED,<br>        updateQuery: (prev, { subscriptionData }) =&gt; {<br>            <strong>const </strong>data: AuthorMutated = subscriptionData.data;<br>            <strong>if </strong>(!data) <strong>return </strong>prev;<br><br>            <strong>const </strong>authorMutated = data.authorMutated;<br><br>            <strong>switch </strong>(authorMutated.mutation) {<br>                <strong>case </strong>MutationType.<em>CREATED</em>: {<br>                    <strong>const </strong>newAuthor = authorMutated.node;<br>                    // Don&#39;t double add the author<br>                    <strong>if </strong>(findAuthor(prev.authors, newAuthor.id)) {<br>                        <strong>return </strong>prev;<br>                    } <strong>else </strong>{<br>                        // Author not found, add it<br>                        <strong>return </strong>Object.assign({}, prev, {<br>                            authors: [...prev.authors, newAuthor]<br>                        });<br>                    }<br>                }<br>                <strong>case </strong>MutationType.<em>UPDATED</em>: {<br>                    <strong>const </strong>updatedAuthor = authorMutated.node;<br>                    // Replace previous author with updated one<br>                    <strong>return </strong>Object.assign({}, prev, {<br>                        authors: prev.authors.map(author =&gt;<br>                            author.id === updatedAuthor.id<br>                                ? updatedAuthor<br>                                : author<br>                        )<br>                    });<br>                }<br>                <strong>case </strong>MutationType.<em>DELETED</em>: {<br>                    <strong>const </strong>deletedAuthor = authorMutated.node;<br>                    // Delete author<br>                    <strong>return </strong>Object.assign({}, prev, {<br>                        authors: prev.authors.filter(<br>                            author =&gt; author.id !== deletedAuthor.id<br>                        )<br>                    });<br>                }<br>                <strong>default</strong>:<br>                    <strong>return </strong>prev;<br>            }<br>        }<br>    });<br>}</pre><p>The subscribeToAuthorMutations() function does the actual subscription to the authorMutated event by calling subscribeToMore. The updateQuery callback is called whenever a new authorMutated event is received. The callback then updates the Apollo cache based on the mutation type. This in turn refreshes the view and shows the result of the mutation.</p><h3>Summary</h3><p>We have now covered everything to do with subscriptions on the client. This is what we learned:</p><ul><li>How to declare subscriptions on the client</li><li>How to subscribe to subscription events</li><li>How to update the Apollo cache when a subscribed event is received</li></ul><p>With this, you should feel empowered to write your own GraphQL applications from scratch. If you have any questions or comments, I’d love to hear from you.</p><p>If you found this series helpful, please share it with your fellow developers. Until then, happy computing!</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b84203fb0b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/62ec468b44ba</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Wed, 26 Dec 2018 04:40:36 GMT</pubDate>
            <atom:updated>2018-12-27T02:39:25.147Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 6: Subscriptions (server implementation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQRIrvEHJ1gAaVReOWjX3A.png" /><figcaption>Image by <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a></figcaption></figure><p><em>In part 5 of this series we implemented mutations on the Bookstore client. In this part, we jump back to the server side and implement subscriptions.</em></p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><strong>Part 6: Subscriptions (server implementation)</strong></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><p><em>One part will be released every day this week. </em><a href="https://twitter.com/NareshJBhatia"><em>Follow me</em></a><em> or </em><a href="https://contentupgrade.me/kKpZYZJj"><em>subscribe to my newsletter</em></a><em> to get updates on this series.</em></p><h3>Source Code</h3><p>You can download the code for this part by executing the following commands. Skip the first command if you have already cloned the repository.</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout 6-subscriptions-server</pre><h3>Test Drive</h3><p>Before diving into the implementation, let’s look at how the final implementation works. Make sure you have <a href="https://yarnpkg.com/">yarn</a> installed on your machine. Now execute the following commands:</p><pre>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><p>This will start the server. Point your browser to <a href="http://localhost:4000/">http://localhost:4000/</a> — it will show the <a href="https://github.com/prisma/graphql-playground">GraphQL Playground</a>. You’ve already used the Playground in part 2, so it needs no introduction.</p><p>Remember, subscriptions are a way to display changes in real time. Our discussion from part 1 states:</p><blockquote>GraphQL subscriptions are a way to push data from the server to the clients in real-time. As defined by the GraphQL specification: “subscription is a long‐lived request that fetches data in response to source events”. In fact, subscriptions are very similar to queries in that they specify a set of fields to be returned. However, instead of returning them immediately, the server sends them to the requesting client every time a specified event happens.</blockquote><p>Let’s start by looking at a subscription operation declared in the updated schema. Here’s the authorMutated subscription:</p><pre><strong>type </strong>Subscription {<br>    authorMutated: AuthorMutationPayload!<br>}<br><br><strong>type </strong>AuthorMutationPayload {<br>    mutation: MutationType!<br>    node: Author!<br>}</pre><pre><strong>enum </strong>MutationType {<br>    CREATED<br>    UPDATED<br>    DELETED<br>}</pre><p>Here’s how to interpret this declaration:</p><p>If a client subscribes to the authorMutated event, it will be sent the AuthorMutationPayload whenever that event happens. AuthorMutationPayload is an object with two fields:</p><ul><li><strong>mutation</strong>: indicates what type of mutation was performed: CREATED, UPDATED or DELETED</li><li><strong>node</strong>: The author that was created, updated or deleted</li></ul><p>With this background, let’s subscribe to the authorMutated event from the Playground. In the left panel, enter the following subscription and click the <em>Execute</em> button.</p><pre>subscription {<br>  authorMutated {<br>    mutation<br>    node {<br>      id<br>      name<br>    }<br>  }<br>}</pre><p>The right panel will now show “Listening …”.</p><p>Open a new tab in Playground and create an author by entering this mutation</p><pre>mutation CreateAuthor($name: String!) {<br>  createAuthor(name: $name) {<br>    id,<br>    name<br>  }<br>}</pre><p>along with the following query variable:</p><pre>{<br>  &quot;name&quot;: &quot;Walter Isaacson&quot;<br>}</pre><p>When the author is successfully created, switch back to the subscription tab. You will see the following subscription response. Note that the mutation type is CREATED.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;authorMutated&quot;: {<br>      &quot;mutation&quot;: &quot;CREATED&quot;,<br>      &quot;node&quot;: {<br>        &quot;id&quot;: &quot;4otdl&quot;,<br>        &quot;name&quot;: &quot;Walter Isaacson&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Now open another tab in Playground and update the name of the author by entering the following mutation:</p><pre>mutation UpdateAuthor($authorId: ID!, $name: String!) {<br>  updateAuthor(authorId: $authorId, name: $name) {<br>    id,<br>    name<br>  }<br>}</pre><p>along with the following query variables (<strong><em>use the author id that you received</em></strong>):</p><pre>{<br>  &quot;authorId&quot;: &quot;4otdl&quot;,<br>  &quot;name&quot;: &quot;W Isaacson&quot;<br>}</pre><p>When the author is successfully updated, switch back to the subscription tab. You will see the following subscription response. Note that the mutation type is UPDATED.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;authorMutated&quot;: {<br>      &quot;mutation&quot;: &quot;UPDATED&quot;,<br>      &quot;node&quot;: {<br>        &quot;id&quot;: &quot;4otdl&quot;,<br>        &quot;name&quot;: &quot;W Isaacson&quot;<br>      }<br>    }<br>  }<br>}</pre><h3>Subscription Implementation</h3><h4>Declaring the schema</h4><p>The first step to implement a subscription is to declare it in our schema. We’ve already seen the declaration for the authorMutated subscription. Look over the declarations of publisherMutated and bookMutated — they are similar.</p><h4>Creating up a PubSub instance</h4><p>The next step is to create a PubSub instance which is responsible for managing subscriptions on the server. PubSub is a class that exposes a publish and a subscribe API. Here’s the code that creates a global PubSub instance to be used in our server:</p><pre># ----- graphql/pubsub.ts -----</pre><pre><strong>import </strong>{ PubSub } <strong>from </strong>&#39;apollo-server&#39;;<br><strong>export const </strong>pubsub = <strong>new </strong>PubSub();</pre><h4>Creating subscription resolvers</h4><p>Just like other schema fields, we need to create resolvers for our subscription operations. However, instead of a function, the subscription resolvers requires an object with a subscribe method that return an AsyncIterator. We obtain the AsyncIterator using our global pubsub object. This iterator is responsible for emitting published messages to all the subscribed clients.</p><p>Putting this together, here’s the authorMutated resolver.</p><pre># ----- graphql/resolvers/author-resolvers.ts -----</pre><pre>Subscription: {<br>    authorMutated: {<br>        subscribe: () =&gt; pubsub.asyncIterator(AUTHOR_MUTATED)<br>    }<br>}</pre><p>The other subscription resolvers are similar. Take a look to see if they make sense.</p><h4>Publishing subscription events</h4><p>Now that we’ve provided a mechanism for clients to subscribe to events, the only thing left is to publish those events. For example, we need to publish the AUTHOR_MUTATED event whenever an author is created or updated. Let’s enhance the mutation resolvers to do exactly that.</p><pre># ----- graphql/resolvers/author-resolvers.ts -----</pre><pre>Mutation: {<br>    createAuthor(parent, args) {<br>        <strong>return </strong>dataSources.bookService<br>            .createAuthor({<br>                name: args.name<br>            })<br>            .then(author =&gt; {<br>                pubsub.publish(AUTHOR_MUTATED, {<br>                    authorMutated: {<br>                        mutation: &#39;CREATED&#39;,<br>                        node: author<br>                    }<br>                });<br>                <strong>return </strong>author;<br>            });<br>    },<br>    updateAuthor(parent, args) {<br>        <strong>return </strong>dataSources.bookService<br>            .updateAuthor(args.authorId, {<br>                name: args.name<br>            })<br>            .then(author =&gt; {<br>                pubsub.publish(AUTHOR_MUTATED, {<br>                    authorMutated: {<br>                        mutation: &#39;UPDATED&#39;,<br>                        node: author<br>                    }<br>                });<br>                <strong>return </strong>author;<br>            });<br>    }<br>}</pre><p>Here we call pubSub.publish() to publish theAUTHOR_MUTATED event along with the desired payload.</p><h4>Scaling subscriptions</h4><p>By default, the Apollo Server uses a PubSub implementation provided by <a href="https://github.com/apollographql/graphql-subscriptions">graphql-subscriptions</a>. This implementation does not scale well as described in the docs:</p><blockquote>Note that the default PubSub implementation is intended for demo purposes. It only works if you have a single instance of your server and doesn’t scale beyond a couple of connections. For production usage you’ll want to use one of the PubSub implementations backed by an external store. (e.g. Redis)</blockquote><p>To scale subscriptions beyond a single GraphQL server, we need a more robust pub/sub mechanism that can distribute published messages over multiple GraphQL servers. Here’s the logical architecture for such a system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAsN0-NKTLniSt3pZRhyUg.png" /><figcaption>Scaling subscriptions</figcaption></figure><p>Note that in this architecture there are event sources and listeners other than the GraphQL servers themselves, e.g. the two micro-services shown on the left. In fact, if we upgrade to this architecture for our bookstore, I would recommend having a Bookstore micro-service. This micro-service would connect to our persistence data store and be responsible for all the CRUD operations. Moreover, publishing mutation events (which is currently happening inside the GraphQL resolvers) would move to the Bookstore micro-service, which is now responsible for mutations. In this scenario, the GraphQL servers will only subscribe to mutation events.</p><p>Let’s use the publish/subscribe capabilities of Redis to implement just the event bus for now (not the full architecture). We will switch to the <a href="https://github.com/davidyaha/graphql-redis-subscriptions">graphql-redis-subscriptions</a> library to do this. Follow the steps below:</p><ol><li>Install and start a Redis server. Here’s an <a href="https://1upnote.me/post/2018/06/install-config-redis-on-mac-homebrew/">article</a> that describes how to install Redis on MacOS.</li><li>Open graphql/pubsub.ts. Comment out the default PubSub implementation (lines 2–3) and uncomment the Redis implementation (lines 7–8).</li><li>Restart the Bookstore server.</li></ol><p>Now subscriptions will use the Redis server for publish/subscribe. This will scale significantly better.</p><h3>Summary</h3><p>We’ve now covered the subscription implementation on the server. This is what we learned:</p><ul><li>How to declare subscriptions in our schema</li><li>How to create a PubSub instance to support subscriptions</li><li>How to write a subscription resolver</li><li>How to publish subscription events</li><li>How to scale subscriptions using a Redis implementation of PubSub</li></ul><p>With only one part left in the series, I’d love to get your questions and comments.</p><p>In part 7, we will implement subscriptions in our React client.</p><h4><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Read Part 7: Subscriptions (client implementation) &gt;</a></h4><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">GraphQL concepts I wish someone explained to me a year ago</a></p><h3>Resources</h3><ul><li><a href="https://www.youtube.com/watch?v=Wi7P39sF2nw">GraphQL Subscriptions</a> by <a href="https://medium.com/u/3e6b69951eef">Robert Zhu</a>: In this presentation, Robert starts from the official (abstract) definition of subscriptions and explains what it means in practical terms.</li><li><a href="https://www.youtube.com/watch?v=Wi7P39sF2nw">GraphQL Subscriptions</a> by <a href="https://medium.com/u/d844f9bb25b8">Urigo</a>: Uri demystifies the magic behind GraphQL subscriptions and shows how anyone can implement them.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ec468b44ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/61923646739b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Tue, 25 Dec 2018 00:31:52 GMT</pubDate>
            <atom:updated>2018-12-28T18:15:42.231Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 5: Mutations (client implementation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcNKD1-gnMdgSrqrZ6fA8A.png" /><figcaption>Image by <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a></figcaption></figure><p><em>In part 4 of this series we implemented mutations on our Bookstore server. In this part, we jump back to the client side and implement matching mutations there.</em></p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><strong>Part 5: Mutations (client implementation)</strong></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><p><em>One part will be released every day this week. </em><a href="https://twitter.com/NareshJBhatia"><em>Follow me</em></a><em> or </em><a href="https://contentupgrade.me/kKpZYZJj"><em>subscribe to my newsletter</em></a><em> to get updates on this series.</em></p><h3>Source Code</h3><p>You can download the code for this part by executing the following commands. Skip the first command if you have already cloned the repository.</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout 5-mutations-client</pre><h3>Test Drive</h3><p>Before diving into the implementation, let’s look at how the final implementation works. Make sure you have <a href="https://yarnpkg.com/">yarn</a> installed on your machine. Now execute the following commands:</p><pre>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><p>This starts the server. In a different shell, execute the following commands to start the client:</p><pre>cd apollo-bookstore-client<br>yarn<br>yarn start</pre><p>Point your browser to <a href="http://localhost:3000/">http://localhost:3000/</a>. You should see the familiar GraphQL Bookstore client. What’s new from last time? You should now be able to create and edit all the bookstore entities. Give it a try.</p><blockquote><strong>Side note</strong><br>Due to a minor bug that creeped into this commit, the create use case will not work very well. It’s performing the correct mutation on the server. It’s also receiving the newly created entity back, which is saved in the Apollo Cache. However, the list appears to be unchanged because MobX observers prevent re-renderings when the props of a component have only shallowly changed.</blockquote><blockquote>This bug has been fixed in the master branch by sending the full data object returned by queries to AuthorsPanel, PublishersPanel and BooksPanel (instead of just the contained list). You can checkout the master branch to verify this.</blockquote><h3>Mutation Implementation</h3><h4>Download schema and run codegen</h4><p>Since the schema on the server has changed, we need to run the gql:schema script again. Also, as we add mutations in the client, we need to run the gql:types script to generate new TypeScript type definitions.</p><h4>Add mutations to the AuthorsPanel</h4><p>The AuthorsPanel is where all the author mutations are triggered:</p><ul><li>When the <em>Add</em> button is clicked in the AuthorsPanel, the AuthorDialog is displayed. When the user clicks the save button on the dialog, the createAuthor mutation is triggered.</li><li>When a row in the author table is clicked, the AuthorDialog is displayed, pre-populated with the author that was clicked. When the user clicks the save button on the dialog, the updateAuthor mutation is triggered.</li></ul><p>Let’s see how this is implemented. We first add the create and update mutations at the end of authors-panel.tsx:</p><pre><strong>const </strong>CREATE_AUTHOR = gql`<br>    mutation CreateAuthor($name: String!) {<br>        createAuthor(name: $name) {<br>            id<br>            name<br>        }<br>    }<br>`;<br><br><strong>const </strong>UPDATE_AUTHOR = gql`<br>    mutation UpdateAuthor($authorId: ID!, $name: String!) {<br>        updateAuthor(authorId: $authorId, name: $name) {<br>            id<br>            name<br>        }<br>    }<br>`;</pre><p>We then add two sections in the render() method to show the AuthorDialog in the create and update case. Below we show the code for the create case (the update case is similar):</p><pre>{<strong>this</strong>.showAuthorDialog &amp;&amp; <strong>this</strong>.isNewAuthor &amp;&amp; (<br>    &lt;Mutation mutation={CREATE_AUTHOR}&gt;<br>        {createAuthor =&gt; (<br>            &lt;AuthorDialog<br>                author={<strong>this</strong>.editedAuthor}<br>                onSave={author =&gt; {<br>                    createAuthor({<br>                        variables: {<br>                            name: author.name<br>                        },<br>                        // Update AuthorsQuery in Apollo cache<br>                        // Needed only in this &quot;Create&quot; case<br>                        update: (<br>                            store,<br>                            { data: { createAuthor } }<br>                        ) =&gt; {<br>                            <strong>const </strong>data = store.readQuery({<br>                                query: GET_AUTHORS<br>                            }) <strong>as any</strong>;<br>                            data.authors.push(createAuthor);<br>                            store.writeQuery({<br>                                query: GET_AUTHORS,<br>                                data<br>                            });<br>                        }<br>                    });<br>                    <strong>this</strong>.hideAuthorDialog();<br>                }}<br>                onCancel={<strong>this</strong>.hideAuthorDialog}<br>            /&gt;<br>        )}<br>    &lt;/Mutation&gt;<br>)}</pre><p>Note that AuthorDialog is wrapped in the &lt;Mutation&gt; component provided by Apollo. It works in a similar way to the &lt;Query&gt; component that we discussed in part 3. Essentially, the &lt;Mutation&gt; component takes a GraphQL mutation as a prop and calls the render prop passing it the createAuthor function. When the user clicks the <em>Save</em> button in the AuthorDialog, the onSave method initiates a mutation by calling this createAuthor method. The createAuthor method also accepts an update function which is called on a successful update. This method is passed a reference to the store (Apollo cache) as well as the result sent by the server (the newly created author). We use these arguments to update the local Apollo cache using the readQuery and writeQuery methods.</p><p>Now that you understand how mutations work in the AuthorsPanel, it should be straightforward to understand how they work in the PublishersPanel and the BooksPanel.</p><h3>Summary</h3><p>We have now covered our basis with mutations on the client. This is what we’ve learned:</p><ul><li>How to declare mutations on the client</li><li>How to trigger the mutation queries using Apollo’s &lt;Mutation&gt; component</li></ul><p>We’re on the home stretch now–are you enjoying the series so far? I’d love to get your questions and comments.</p><p>In part 6, we will dive into subscriptions and add them to the Bookstore server.</p><h4><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Read Part 6: Subscriptions (server implementation) &gt;</a></h4><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">GraphQL concepts I wish someone explained to me a year ago</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61923646739b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago [Series Update]]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-series-update-7b028fd6f682?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/7b028fd6f682</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apollo]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 05:20:48 GMT</pubDate>
            <atom:updated>2018-12-24T05:20:48.659Z</atom:updated>
            <content:encoded><![CDATA[<p>First off, thanks so much to all of you who subscribed this week. I’m trying something new — this is my first newsletter and I’m looking forward to your feedback as we go along.</p><p>We’ve covered a lot of ground this week in GraphQL. We’re now more than half way through our series.</p><h3>Did you download the source code for <a href="https://github.com/nareshbhatia/graphql-bookstore">graphql-bookstore</a>?</h3><p>If you haven’t yet, it’s OK. Each part of the series is tagged with a git tag. You can run the full application using the instructions below:</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore</pre><pre># ----- In shell 1 -----<br>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><pre># ----- In shell 2 -----<br>cd apollo-bookstore-client<br>yarn<br>yarn start</pre><p>And now you’re almost ready to go fully offline…</p><h3>Have you queued up all the articles before your holiday trip?</h3><p>I know it always takes me some time to get organized before traveling. Here are links to each part of the series, in case you missed one:</p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a> <em>[just released today]</em></li></ul><h3>If you’re already caught up to this point…</h3><p>You’re an example to all of us :) I’d love to get your questions and comments.</p><p>Coming up next, we have mutations (client implementation), and subscriptions. Stay tuned!</p><p>Until then, happy computing and happy holidays.</p><p>-Naresh</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b028fd6f682" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-series-update-7b028fd6f682">GraphQL concepts I wish someone explained to me a year ago [Series Update]</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/572d47318e17</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 02:22:35 GMT</pubDate>
            <atom:updated>2018-12-27T02:39:29.509Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 4: Mutations (server implementation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ObN-2XmbeUIEX-Im71blQ.png" /><figcaption>Image by <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a></figcaption></figure><p><em>In part 3 of this series we implemented a React app that could send GraphQL queries to our Bookstore server. In this part, we jump back to the server side and implement mutations.</em></p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><strong>Part 4: Mutations (server implementation)</strong></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><p><em>One part will be released every day this week. </em><a href="https://twitter.com/NareshJBhatia"><em>Follow me</em></a><em> or </em><a href="https://contentupgrade.me/kKpZYZJj"><em>subscribe to my newsletter</em></a><em> to get updates on this series.</em></p><h3>Source Code</h3><p>You can download the code for this part by executing the following commands. Skip the first command if you have already cloned the repository.</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout 4-mutations-server</pre><h3>Test Drive</h3><p>Before diving into the implementation, let’s look at how the final implementation works. Make sure you have <a href="https://yarnpkg.com/">yarn</a> installed on your machine. Now execute the following commands:</p><pre>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><p>This will start the server. Point your browser to <a href="http://localhost:4000/">http://localhost:4000/</a> — it will show the <a href="https://github.com/prisma/graphql-playground">GraphQL Playground</a>. You have already used the Playground in part 2, so it needs no introduction.</p><p>Let’s start by creating a new author. Enter the following mutation in the left panel of the Playground.</p><pre>mutation CreateAuthor($name: String!) {<br>  createAuthor(name: $name) {<br>    id,<br>    name<br>  }<br>}</pre><p>This mutation introduces the concept of <em>query variables</em>. Instead of hard coding the name of the author in the mutation, we will pass it as a query variable — that’s what $name is. So how do we do that? Click on the QUERY VARIABLES button at the bottom of the Playground. It will pop up a panel where you can enter query variables. Enter the $name variable as follows:</p><pre>{<br>  &quot;name&quot;: &quot;Walter Isaacson&quot;<br>}</pre><p>Now click on the <em>Execute</em> button to execute the mutation. You should see the result in the right panel, showing the newly created author. Make a note of the author id — it will be a different string for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*_eAtaHpHYPIh2USzZ9f4rg.png" /><figcaption>Creating a new author using Playground</figcaption></figure><p>The syntax of mutations looks almost identical to queries, the main difference being that they must start with the mutation keyword. The arguments passed into the mutation (in this case name) is all that the server needs to perform the mutation (create, update or delete). As with queries, if the mutation returns an object, you can ask for nested fields. This can be useful for fetching the new state of an object after an update. For example, in an update mutation, we can ask for the author + the books they have written.</p><p>Let’s perform a few more mutations to understand the mutation API. Execute the following mutation to create a publisher:</p><pre>mutation CreatePublisher($name: String!) {<br>  createPublisher(name: $name) {<br>    id,<br>    name<br>  }<br>}</pre><p>Supply it with the following query variables:</p><pre>{<br>  &quot;name&quot;: &quot;Simon &amp; Schuster&quot;<br>}</pre><p>Heres’ the result I got. Again, note the publisher id you get.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createPublisher&quot;: {<br>      &quot;id&quot;: &quot;g64j1l&quot;,<br>      &quot;name&quot;: &quot;Simon &amp; Schuster&quot;<br>    }<br>  }<br>}</pre><p>Now let’s create a book using the newly created author and publisher. Here’s the mutation for it:</p><pre>mutation CreateBook($book: BookInput!) {<br>  createBook(book: $book) {<br>    id,<br>    name,<br>    publisher {<br>      name<br>    }<br>  }<br>}</pre><p>Here BookInput is not a scalar like we have seen in the other mutations. It’s an input object type, a special kind of object type that can be passed in as an argument. Here’s how we have defined BookInput in our GraphQL schema:</p><pre><strong>input </strong>BookInput {<br>    name: String!<br>    publisherId: ID!<br>}</pre><p>Let’s supply BookInput as a query variable in the Playground and click the <em>Execute</em> button. <strong><em>Make sure you enter the publisher id that you got earlier</em></strong><em>.</em></p><pre>{<br>  &quot;book&quot;: {<br>    &quot;name&quot;: &quot;Steve Jobs&quot;,<br>    &quot;publisherId&quot;: &quot;g64j1l&quot;<br>  }<br>}</pre><p>The result is shown below. We have successfully created a book. Again, note the book id you get.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createBook&quot;: {<br>      &quot;id&quot;: &quot;fswi5p&quot;,<br>      &quot;name&quot;: &quot;Steve Jobs&quot;,<br>      &quot;publisher&quot;: {<br>        &quot;name&quot;: &quot;Simon &amp; Schuster&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Note that this mutation has been designed to create a book with minimal amount of input — the book’s name and the publisher id. You’ll notice the authors have not been specified. So let’s execute another mutation to add an author:</p><pre>mutation SetBookAuthors($bookId: ID!, $authorIds: [ID!]!) {<br>  setBookAuthors(bookId: $bookId, authorIds: $authorIds) {<br>    id<br>    name<br>    authors {<br>      name<br>    }<br>  }<br>}</pre><p>Enter the query variables as follows (<strong><em>make sure you enter the ids that you got</em></strong>):</p><pre>{<br>  &quot;bookId&quot;: &quot;fswi5p&quot;,<br>  &quot;authorIds&quot;: [<br>    &quot;3a7ae&quot;<br>  ]<br>}</pre><p>And here’s the result I got — the book <em>Steve Jobs</em> written by <em>Walter Isaacson</em>:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;setBookAuthors&quot;: {<br>      &quot;id&quot;: &quot;fswi5p&quot;,<br>      &quot;name&quot;: &quot;Steve Jobs&quot;,<br>      &quot;authors&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Walter Isaacson&quot;<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>Update mutations are very similar, they generally require an additional argument — the identifier of the object you want to mutate. Try them out yourself. Use the extended Bookstore schema as your guide.</p><h3>Mutation Implementation</h3><h4>Extending type definitions</h4><p>First off, we need to add mutation type definitions to our schema. Here are the updates to the three type definition modules:</p><pre># ----- author.graphql -----<br><strong>type </strong>Mutation {<br>    createAuthor(name: String!): Author!<br>    updateAuthor(authorId: ID!, name: String!): Author!<br>}</pre><pre># ----- publisher.graphql -----<br><strong>type </strong>Mutation {<br>    createPublisher(name: String!): Publisher!<br>    updatePublisher(publisherId: ID!, name: String!): Publisher!<br>}</pre><pre># ----- book.graphql -----<br><strong>type </strong>Mutation {<br>    createBook(book: BookInput!): Book!<br>    updateBook(bookId: ID!, book: BookInput!): Book!<br>    setBookAuthors(bookId: ID!, authorIds: [ID!]): Book!<br>}<br><br><strong>input </strong>BookInput {<br>    name: String!<br>    publisherId: ID!<br>}</pre><h4>Adding mutation resolvers</h4><p>Next we need to add resolvers for the new mutation operations. Here’s an example for the author mutations:</p><pre>Mutation: {<br>    createAuthor(parent, args) {<br>        <strong>return </strong>dataSources.bookService.createAuthor({<br>            name: args.name<br>        });<br>    },<br>    updateAuthor(parent, args) {<br>        <strong>return </strong>dataSources.bookService.updateAuthor(args.authorId, {<br>            name: args.name<br>        });<br>    }<br>}</pre><p>Of course we’ll need to add new methods to bookService to support the mutations. For example:</p><pre>createAuthor(authorInput) {<br>    <strong>const </strong>author = Object.assign({}, authorInput, { id: newId() });<br>    authors.push(author);<br>    <strong>return </strong>Promise.resolve(author);<br>}<br><br>updateAuthor(authorId, authorInput) {<br>    <strong>let </strong>author = findAuthor(authorId);<br>    author = author ? Object.assign(author, authorInput) : <strong>null</strong>;<br>    <strong>return </strong>Promise.resolve(author);<br>}</pre><h3>Summary</h3><p>We have now covered the mutation implementation on the server. This is what we learned:</p><ul><li>Mutation syntax and its similarities to query syntax</li><li>The concepts of <em>query variables</em> and <em>input</em> object types</li><li>Adding mutation type definitions to the schema</li><li>Writing resolvers for mutations</li></ul><p>Have you gotten stuck at any point so far? I would love to get your questions and comments.</p><p>In part 5, we will implement mutations in our React client.</p><h4><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Read Part 5: Mutations (client implementation) &gt;</a></h4><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">GraphQL concepts I wish someone explained to me a year ago</a></p><h3>Resources</h3><ul><li><a href="https://medium.com/@__xuorig__/graphql-mutation-design-anemic-mutations-dd107ba70496">GraphQL Mutation Design</a> by <a href="https://medium.com/u/ecb22831abfb">Marc-André Giroux</a>: Explains how to design mutation APIs that don’t feel anemic.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=572d47318e17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/959b234ff430</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Sat, 22 Dec 2018 20:30:08 GMT</pubDate>
            <atom:updated>2020-12-23T18:09:50.953Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: Queries (client implementation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5vjAnK0GHmpHitEWvRFRw.png" /><figcaption>Image by <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a></figcaption></figure><p><em>In part 2 of this series we implemented a GraphQL server that could respond to queries. In this part, we will build a matching client using React.</em></p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><strong>Part 3: Queries (client implementation)</strong></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><p><em>One part will be released every day this week. </em><a href="https://twitter.com/NareshJBhatia"><em>Follow me</em></a><em> or </em><a href="https://contentupgrade.me/kKpZYZJj"><em>subscribe to my newsletter</em></a><em> to get updates on this series.</em></p><h3>Source Code</h3><p>You can download the code for this part by executing the following commands. Skip the first command if you have already cloned the repository.</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout 3-queries-client</pre><h3>Test Drive</h3><p>Before diving into the implementation, let’s look at how the final implementation works. Make sure you have <a href="https://yarnpkg.com/">yarn</a> installed on your machine. Now execute the following commands:</p><pre>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><p>This starts the server. In a different shell, execute the following commands to start the client:</p><pre>cd apollo-bookstore-client<br>yarn<br>yarn start</pre><p>Point your browser to <a href="http://localhost:3000/">http://localhost:3000/</a>. You should see the GraphQL Bookstore client. It shows all the bookstore entities and relationships on a single page. This will allow us to demonstrate several GraphQL features — for example, how Apollo Cache normalizes entities to keep views consistent across the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTWVyppk7J2rskcGW8gGKA.png" /><figcaption>GraphQL Bookstore client</figcaption></figure><h3>Client Implementation</h3><p>The client has been created using <a href="https://facebook.github.io/create-react-app/">create-react-app</a>. I am using TypeScript to benefit from type checking. The UI has been created using <a href="https://material-ui.com/">Material UI</a>. I am also using <a href="https://github.com/nareshbhatia/mobx-state-router">mobx-state-router</a> for routing and <a href="https://jaredpalmer.com/formik">formik</a> for form handling. Most importantly, I am using the <a href="https://www.apollographql.com/docs/react/">Apollo Client</a> to send GraphQL queries to the server.</p><blockquote><strong>Side note<br></strong>Apollo offers a slightly simpler starter-kit called <a href="https://github.com/apollographql/apollo-client/tree/master/packages/apollo-boost">Apollo Boost</a>. However, as of this writing, it does not support subscriptions. Hence I chose to use the Apollo Client directly.</blockquote><h4>Setting up Apollo Client</h4><p>In order to use Apollo Client, we need to make it available to any component that needs to send GraphQL queries to the server. This is done at the App level, in the app.tsx file. Here’s the gist of it (I have omitted code that is not relevant to this discussion):</p><pre>// ----- app.tsx -----<br><br>// Create an http link:<br><strong>const </strong>httpLink = <strong>new </strong>HttpLink({<br>    uri: process.env.REACT_APP_HTTP_LINK<br>});<br><br>// Create a WebSocket link:<br><strong>const </strong>wsLink = <strong>new </strong>WebSocketLink({<br>    uri: process.env.REACT_APP_WS_LINK<br>});<br><br><strong>const </strong>link = split(<br>    // split based on operation type<br>    ({ query }) =&gt; {<br>        <strong>const </strong>{ kind, operation } = getMainDefinition(query);<br>        <strong>return </strong>kind === &#39;OperationDefinition&#39; &amp;&amp;<br>               operation === &#39;subscription&#39;;<br>    },<br>    wsLink,<br>    httpLink<br>);<br><br>// Create the Apollo client<br><strong>const </strong>client = <strong>new </strong>ApolloClient({<br>    link: link,<br>    cache: <strong>new </strong>InMemoryCache()<br>});<br><br><strong>export class </strong>App <strong>extends </strong>React.Component {<br>    <strong>public </strong>render() {<br>        <strong>return </strong>(<br>            &lt;ApolloProvider client={client}&gt;<br>                &lt;Shell /&gt;<br>            &lt;/ApolloProvider&gt;<br>        );<br>    }<br>}</pre><p>The first half of the code is essentially creating a link object. The Apollo Client needs a regular HTTP link for queries and mutations and a WebSocket link for subscriptions. Hence we create an httpLink and a wsLink and combine them into a single link object. This link object is then passed into the constructor of ApolloClient. In addition, we send an instance of InMemoryCache, which is a normalized data store. You can read more about it <a href="https://www.apollographql.com/docs/react/advanced/caching.html">here</a>.</p><p>After creating an instance of the ApolloClient, we need to make it available to all the components in the component hierarchy. This is where the ApolloProvider comes in. It places the client in the React context, making it available to all the nested components.</p><h4>Component Hierarchy</h4><p>Now let’s look at the component hierarchy of the application. The main page of the application is called the HomePage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvBYdtDKoo1RV1paelXX6w.png" /><figcaption>Component hierarchy</figcaption></figure><p>HomePage is divided into three panels showing publishers, authors and books. The panels are wrapped by container components, responsible for fetching data from the server and handing it to the panels. The panel components are purely presentational, they know nothing about GraphQL or how the data was fetched (see <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">Presentational and Container Components</a> by <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a>). Let’s see how data is fetched from the server by looking at a sample container component.</p><h4>PublishersContainer</h4><p>PublishersContainer is responsible for fetching the list of all publishers and handing it to the PublishersPanel for display.</p><pre># ----- components/publishers/publishers-container.tsx -----</pre><pre><strong>import </strong>{ DefaultQuery } <strong>from </strong>&#39;..&#39;;<br><strong>import </strong>{ PublishersPanel } <strong>from </strong>&#39;./publishers-panel&#39;;<br><strong>import </strong>{ GET_PUBLISHERS } <strong>from </strong>&#39;./publishers-queries&#39;;<br><br><strong>export class </strong>PublishersContainer <strong>extends </strong>React.Component {<br>    render() {<br>        <strong>return </strong>(<br>            &lt;DefaultQuery query={GET_PUBLISHERS}&gt;<br>                {({ data: { publishers } }) =&gt; {<br>                    <strong>return </strong>&lt;PublishersPanel<br>                            publishers={publishers} /&gt;;<br>                }}<br>            &lt;/DefaultQuery&gt;<br>        );<br>    }<br>}</pre><p>The heart of PublishersContainer is the nested &lt;DefaultQuery&gt; component. It takes a GraphQL query as a prop and calls the render function that is provided as a child. The render function is called with an object containing a data property that holds the query result. You might recognize this pattern as the popular <a href="https://reactjs.org/docs/render-props.html">Render Props</a> pattern. The render function in turn calls PublishersPanel with the query result.</p><p>The DefaultQuery component itself is a thin wrapper around Apollo’s <a href="https://www.apollographql.com/docs/react/essentials/queries.html#basic">Query</a> component. It abstracts away a couple of common tasks we want to do for every query: (1) show a loading message and (2) show any errors returned by the query. Here’s the code for DefaultQuery:</p><pre># ----- components/basics/default-query.tsx -----</pre><pre><strong>import </strong>{ Query } <strong>from </strong>&#39;react-apollo&#39;;<br><strong>import </strong>{ CenteredMessage } <strong>from </strong>&#39;./centered-message&#39;;<br><br><strong>export const </strong>DefaultQuery = ({ query, variables = {}, children }) =&gt; (<br>    &lt;Query query={query} variables={variables}&gt;<br>        {({ loading, error, data, fetchMore, subscribeToMore }) =&gt; {<br>            <strong>if </strong>(loading) {<br>                <strong>return</strong> (<strong><br>                    </strong>&lt;CenteredMessage&gt;<br>                        Loading...<br>                    &lt;/CenteredMessage&gt;<br>                );<br>            }<br><br>            <strong>if </strong>(error) {<br>                <strong>return</strong> (<strong><br>                    </strong>&lt;CenteredMessage&gt;<br>                        {error.message}<br>                    &lt;/CenteredMessage&gt;<br>                );<br>            }<br><br>            <strong>return </strong>children({ data, fetchMore, subscribeToMore });<br>        }}<br>    &lt;/Query&gt;<br>);</pre><p>Finally, lets look at the GET_PUBLISHERS query that is tucked away in a separate module (so that it can be reused):</p><pre># ----- components/publishers/publishers-queries.tsx -----</pre><pre><strong>import </strong>gql <strong>from </strong>&#39;graphql-tag&#39;;<br><br><strong>export const </strong>GET_PUBLISHERS = gql`<br>    query GetPublishers {<br>        publishers {<br>            id<br>            name<br>        }<br>    }<br>`;</pre><p>First off, you will notice that the query string is wrapped in the gql function. This function parses the query string and returns a GraphQL AST (abstract syntax tree). While the query string is easier for humans to read, Apollo Client requires it in the form of an AST. That’s the reason for wrapping the query string with the gql function.</p><p>The second thing you may notice is that we have given a name to the query: GetPublishers. This is not a required part of the GraphQL syntax — we have been using queries in GraphQL Playground without a name. However in the client we will always name our queries so that we can leverage type safety using TypeScript. Here’s how it works:</p><ul><li>We first use the <a href="https://github.com/apollographql/apollo-tooling#apollo-servicedownload-output">Apollo CLI</a> to download the bookstore schema from our GraphQL server. The script to do this is in the client’s package.json file: gql:schema. The schema is saved as schema.json in the client’s root directory and is also committed to the repo. Whenever the schema on the server changes, we must run gql:schema again to update the client’s copy.</li><li>Once we have a local copy of the schema, we must run Apollo CLI’s code generator to generate TypeScript type definitions for all our queries. As mentioned in part 1, query responses contain whatever the query asks for — not the full domain objects. Hence each query is unique and needs unique TypeScript types to describe its inputs and outputs. While this can be done by hand, it would be very tedious and error prone. Hence we use the code generator to generate the types automatically from the queries. The script to generate these type is in the client’s package.json file: gql:types. When this script is run, it parses all the queries in the client and generates TypeScript type definitions in folders named __generated__ relative to where it found the query. For example, here’s the type definition generated for the GetPublishers query:</li></ul><pre>/* tslint:disable */<br>// This file was automatically generated and should not be edited.<br><br>// ====================================================<br>// GraphQL query operation: GetPublishers<br>// ====================================================<br><br><strong>export interface </strong>GetPublishers_publishers {<br>    __typename: &#39;Publisher&#39;;<br>    id: <strong>string</strong>;<br>    name: <strong>string</strong>;<br>}<br><br><strong>export interface </strong>GetPublishers {<br>    publishers: GetPublishers_publishers[];<br>}</pre><p>This needs a bit of explanation. The interface GetPublishers represents the type of the query response. In this case it is an object with one property called publishers which is an array of GetPublishers_publishers. Now that’s a mouthful! Why is the type of publishers GetPublishers_publishers and not just Publisher? Again, in GraphQL we don’t receive the full domain object, we receive only the slice we asked for. Hence this type name was custom created for this specific query. Also note the __typename property of GetPublishers_publishers — it’s an internal property that Apollo Client uses to normalize the cache.</p><p>Now that we know how these types are generated, let’s look at where they’re used next — the PublishersPanel component.</p><h4>PublishersPanel</h4><p>PublishersPanel is responsible for receiving a list of publishers and displaying them. It is a fairy generic React component that uses a Material UI table to display publishers. The only special thing to note is that we are using the generated publisher type to make sure that we are using the publisher list in a type safe way. As a side benefit, it also enables autocompletion in editors that understand TypeScript. Here’s the relevant code in PublishersPanel:</p><pre><strong>import </strong>{ GetPublishers_publishers }<br>    <strong>from </strong>&#39;./__generated__/GetPublishers&#39;;<br><br><strong>export interface </strong>PublishersPanelProps {<br>    publishers: Array&lt;GetPublishers_publishers&gt;;<br>}<br><br><strong>export class </strong>PublishersPanel <strong>extends </strong>React.Component&lt;PublishersPanelProps&gt; {<br>    <strong>public </strong>render() {<br>        <strong>const </strong>{ publishers } = <strong>this</strong>.props;<br><br>        <strong>return </strong>(<br>            &lt;React.Fragment&gt;<br>                ...<br>                {publishers.map(publisher =&gt; (<br>                    &lt;TableRow key={publisher.id}&gt;<br>                        &lt;TableCell&gt;<br>                            {publisher.name}<br>                        &lt;/TableCell&gt;<br>                    &lt;/TableRow&gt;<br>                ))}<br>                ...<br>            &lt;/React.Fragment&gt;<br>        );<br>    }<br>}</pre><h4>BooksContainer</h4><p>Now that you understand PublishersContainer and PublishersPanel, you understand the remaining container and panel components as well — they are essentially the same. The only odd one out is the BooksContainer. The reason is that it needs more information from the server to pass down to the BooksPanel. In addition to the list of books, the BooksPanel requires the list of all publishers and authors. This is so that it can show drop downs of publishers and authors when we are creating and editing books (yes, mutations are coming up next). When I first came across this use case, I was scratching my head because the &lt;Query&gt; component accepts only one query, and I needed three! Fortunately, I found a neat trick in the <a href="https://www.apollographql.com/docs/react/react-apollo-migration.html#compose-to-render-composition">Apollo docs</a> — the &lt;Query&gt; component can be nested to run multiple queries within a single component. So that’s what I did in BooksContainer:</p><pre>&lt;DefaultQuery query={GET_BOOKS}&gt;<br>    {({ data: { books } }) =&gt; {<br>        <strong>return </strong>(<br>            &lt;DefaultQuery query={GET_AUTHORS}&gt;<br>                {({ data: { authors } }) =&gt; (<br>                    &lt;DefaultQuery query={GET_PUBLISHERS}&gt;<br>                        {({ data: { publishers } }) =&gt; (<br>                            &lt;BooksPanel<br>                                books={books}<br>                                authors={authors}<br>                                publishers={publishers}<br>                            /&gt;<br>                        )}<br>                    &lt;/DefaultQuery&gt;<br>                )}<br>            &lt;/DefaultQuery&gt;<br>        );<br>    }}<br>&lt;/DefaultQuery&gt;</pre><p>One more thing we need to look at is the GET_BOOKS query — it’s a little different:</p><pre># ----- components/books/books-queries.ts -----</pre><pre><strong>import </strong>gql <strong>from </strong>&#39;graphql-tag&#39;;<br><br><strong>export const </strong>BOOK_FRAGMENT = gql`<br>    fragment BookFragment on Book {<br>        id<br>        name<br>        publisher {<br>            id<br>            name<br>        }<br>        authors {<br>            id<br>            name<br>        }<br>    }<br>`;<br><br><strong>export const </strong>GET_BOOKS = gql`<br>    query GetBooks {<br>        books {<br>            ...BookFragment<br>        }<br>    }<br><br>    ${BOOK_FRAGMENT}<br>`;</pre><p>Note that the GET_BOOKS query does not list out every field that it wants in the result. Instead it includes a BookFragment. A fragment is simply a shared piece of query logic. We want to return the fields specified in BOOK_FRAGMENT from multiple queries (that we will write later). So we have factored them out into a fragment and we use that fragment in the main GET_BOOKS query.</p><h3>Summary</h3><p>We’ve now covered the full client implementation for queries. Let’s look at what we’ve learned:</p><ul><li>How to set up Apollo Client so that it is available to any component that needs to send out queries</li><li>How to setup our app using the Container and Presentational Components pattern to segregate responsibilities of fetching from displaying data</li><li>How to use Apollo’s &lt;Query&gt; component to execute GraphQL queries</li><li>How to nest the &lt;Query&gt; component to execute multiple queries from a single component</li><li>How to use fragments to factor out common parts of a query</li><li>How to use Apollo CLI to generate TypeScript type definitions</li></ul><p>We’ve built quite a bit so far — are you enjoying the series? I‘d love to get your questions and comments.</p><p>In part 4, we’ll dive into mutations and add them to the Bookstore server.</p><h4><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Read Part 4: Mutations (server implementation) &gt;</a></h4><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">GraphQL concepts I wish someone explained to me a year ago</a></p><h3>Resources</h3><ul><li><a href="https://github.com/nareshbhatia/github-explorer">GitHub Explorer</a>: A slightly more sophisticated application that demonstrates GitHub’s GraphQL API. It uses some elaborate queries and mutations.</li><li><a href="https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm">Apollo Client Developer Tools</a>: A Chrome DevTools extension for Apollo Client. It’s a must have. It provides a built-in GraphiQL console, a query watcher, a mutation inspector and a cache inspector.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959b234ff430" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a55981f3a7e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Fri, 21 Dec 2018 23:13:59 GMT</pubDate>
            <atom:updated>2018-12-27T02:39:34.172Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Queries (server implementation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9ODSGyjWakTEHaiqPdBzQ.png" /><figcaption>Image by <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a></figcaption></figure><p><em>In part 1 of this series we covered the basics of GraphQL. In this part, we will build a GraphQL server that responds queries that we designed in part 1.</em></p><ul><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">Part 1: GraphQL Basics</a></li><li><strong>Part 2: Queries (server implementation)</strong></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><p><em>One part will be released every day this week. </em><a href="https://twitter.com/NareshJBhatia"><em>Follow me</em></a><em> or </em><a href="https://contentupgrade.me/kKpZYZJj"><em>subscribe to my newsletter</em></a><em> to get updates on this series.</em></p><h3>Source Code</h3><p>You can download the code for this part by executing the following commands. Skip the first command if you have already cloned the repository.</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout 2-queries-server</pre><h3>Test Drive</h3><p>Before diving into the implementation, let’s look at how the final implementation works. Make sure you have <a href="https://yarnpkg.com/">yarn</a> installed on your machine. Now execute the following commands:</p><pre>cd apollo-bookstore-server<br>yarn<br>yarn dev</pre><p>This will start the server. Point your browser to <a href="http://localhost:4000/">http://localhost:4000/</a> — it will show an interactive development environment called <a href="https://github.com/prisma/graphql-playground">GraphQL Playground</a>. The Playground allows you to test GraphQL queries, mutations and subscriptions interactively, without having to build a client. You can also browse your schema by clicking on the <em>Schema</em> button.</p><p>Let’s start by performing the authors query. Enter the following query in the left panel and click on the <em>Execute</em> button.</p><pre>{<br>  authors {<br>    id<br>    name<br>  }<br>}</pre><p>You should see the results in the right panel, showing 7 authors that are stored in our data store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yuMrQNKWcoeT9zbOJo0xg.png" /><figcaption>Performing the authors query in Playground</figcaption></figure><p>Now try the more complex query from part 1. This should return the author of Clean Code (Robert C. Martin) and all the books he has written.</p><pre>{<br>  book(id: &quot;clean-code&quot;) {<br>    name<br>    authors {<br>      name<br>      books {<br>        name<br>      }<br>    }<br>  }<br>}</pre><p>Play around by executing your own queries and become familiar with Playground. It’s a very useful tool when developing GraphQL applications.</p><h3>Server Implementation</h3><p>Now that you’ve test-driven the server, let’s dive into the implementation. The Bookstore server uses the <a href="https://www.apollographql.com/docs/apollo-server/">Apollo Server</a> library to implement GraphQL functionality. Apollo Server is a popular choice because it does the heavy lifting for us. Here’s the entry point of our server:</p><pre># ----- apollo-bookstore-server/src/index.ts -----</pre><pre><strong>import </strong>{ ApolloServer } <strong>from </strong>&#39;apollo-server&#39;;<br><strong>import </strong>{ typeDefs } <strong>from </strong>&#39;./graphql/typedefs&#39;;<br><strong>import </strong>{ resolvers } <strong>from </strong>&#39;./graphql/resolvers&#39;;<br><br><strong>const </strong>server = <strong>new </strong>ApolloServer({ typeDefs, resolvers });<br><br>server.listen().then(({ url }) =&gt; {<br>    console.log(`Server ready at ${url}`);<br>});</pre><p>The constructor of ApolloServer takes an options object as its parameter. We’re passing two options into it:</p><ul><li><strong>typedefs</strong>: This is the full GraphQL schema assembled from smaller type definitions stored in multiple modules.</li><li><strong>resolvers</strong>: These are helper functions that assist the Apollo Server to resolve queries, mutations and subscriptions. More about these later.</li></ul><p>After constructing the server object, we simply call its listen() method. This tells the server to listen for GraphQL requests. That’s all there is to the server. Of course, we still need to understand the details behind the typeDefs and the resolvers.</p><blockquote><strong>Side note<br></strong>Normally we would also pass our data sources into the options object. This allows Apollo Server to pass the data sources to the resolvers as context. Unfortunately, at the time of this writing, the Apollo Server fails to do this in case of subscription workflows. Hence I decided not to use this feature for now. Instead I am keeping data sources in a global object that the resolvers can access. You can read more about this issue <a href="https://github.com/nareshbhatia/graphql-bookstore/issues/2">here</a>.</blockquote><h4>Assembling the schema</h4><p>In part 1, we defined the bookstore schema in three modules: author.graphql, publisher.graphql and book.graphql. Now we need to stitch together these modules into a single schema so we can hand it to the Apollo Server. We’ll use a library called <a href="https://github.com/okgrow/merge-graphql-schemas">merge-graphql-schemas</a> to do this (there are several open-source solutions available — this one is super simple and popular). See the code below:</p><pre># ----- graphql/typedefs.ts -----</pre><pre><strong>import </strong>{ fileLoader, mergeTypes } <strong>from </strong>&#39;merge-graphql-schemas&#39;;<br><strong>import </strong>* <strong>as </strong>path <strong>from </strong>&#39;path&#39;;<br><br><strong>const </strong>typesArray = fileLoader(path.join(__dirname, &#39;./typedefs&#39;));<br><br><strong>export const </strong>typeDefs = mergeTypes(typesArray, { all: <strong>true </strong>});</pre><p>We use the fileLoader function to import all files from the <em>typedefs</em> folder. Then we merge the types into a single exported variable called typeDefs.</p><h4>Implementing Resolvers</h4><p>Remember, the Apollo server needs <em>resolver</em> functions to resolve queries, mutations and subscriptions. Let’s understand what these functions are.</p><p>When the server receives a query, it calls the resolver function specifically responsible for that query. The resolver function has the ability to fetch data from one or more data sources to satisfy the query. The returned data may include one or more nodes from the universal object graph. However, depending on the query, the server will need to dig deeper into these objects and collect their fields and related objects. Each of these deeper questions needs a dedicated resolver. The server will call these resolvers in a breadth-first search manner, following the structure of the query.</p><p>Let’s understand this mechanism by using the book query shown above. Here’s the series of questions the server must ask:</p><pre>Give me the book with id=&quot;clean-code&quot;<br>  Give me the book&#39;s name<br>  Give me the book&#39;s authors<br>    Give me the author&#39;s name<br>    Give me all the books the author has written<br>      Give me the book&#39;s name</pre><blockquote><strong>Side note<br></strong>As you can see, each field in the GraphQL schema must be backed by a resolver. This includes not only the fields of our domain entities, but also the queries — after all, queries are also the fields of the root Query type. The resolver’s job is to fetch the requested data from data sources and return it to the server.</blockquote><p>Before we can start writing resolvers, we need to understand what a resolver function looks like. Resolver functions accept four arguments and return data:</p><pre>fieldName: (parent, args, context, info) =&gt; data</pre><p>Let’s use the following query to understand what gets passed into each argument:</p><pre>{<br>  author(id: &quot;eric-evans&quot;) {<br>    name<br>  }<br>}</pre><ul><li><strong>parent</strong>: Recall, the GraphQL server performs a breadth-first traversal to create the query response. At each level it calls a resolver. The parent argument of the resolver is simply the result returned by the resolver at the previous level. The call to the root level resolver receives a <em>null</em> in this argument. For the query above, the author resolver receives a <em>null</em> as the parent argument whereas the name resolver receives the result of the author resolver.</li><li><strong>args</strong>: An object containing the arguments passed to the field. For the query above, the author resolver will receive { id: “eric-evans&quot; } as the args argument whereas the name resolver will receive a blank object.</li><li><strong>context</strong>: An object shared by all resolvers in a GraphQL operation. It can be used to pass any information that all resolvers need, e.g. per-request state (such as authentication information) or reference to data sources.</li><li><strong>info</strong>: An abstract syntax tree (AST) representation of the query or mutation — used only in advanced use cases.</li></ul><p>Armed with this knowledge, we should be able to write our resolvers. Again, in the interest of modularity, we will create a separate file for each entity’s resolvers. Let’s start with author resolvers. We will let the author typeDefs guide what resolvers we need to write. Remember that we need one resolver for every field. For reference, here are the author type definitions from part 1:</p><pre><strong>type </strong>Query {<br>    authors: [Author!]!<br>    author(id: ID!): Author!<br>}</pre><pre><strong>type </strong>Author {<br>    id: ID!<br>    name: String!<br>    books: [Book!]!<br>}</pre><p>Based on these type definitions, below is the code for author resolvers:</p><pre># ----- graphql/resolvers/author-resolvers.ts -----</pre><pre><strong>import </strong>{ dataSources } <strong>from </strong>&#39;../../datasources&#39;;<br><br><strong>export default </strong>{<br>    Query: {<br>        authors() {<br>            <strong>return </strong>dataSources.bookService.getAuthors();<br>        },<br><br>        author(parent, args) {<br>            <strong>return </strong>dataSources.bookService.getAuthor(args.id);<br>        }<br>    },<br><br>    Author: {<br>        id(parent, args) {<br>            <strong>return </strong>parent.id;<br>        },<br><br>        name(parent, args) {<br>            <strong>return </strong>parent.name;<br>        },</pre><pre>        books(parent) {<br>            <strong>return </strong>dataSources<br>                .bookService.getAuthorBooks(parent.id);<br>        }<br>    }<br>};</pre><p>Starting at the very top, we import dataSources. This contains references to services that allow us to fetch data. It is a best practice not to pollute the resolvers with low-level data fetching code. Hence all the fetching code has been separated out into its own layer. This approach allows us to switch database technologies without affecting the rest of the server. Moreover, it keeps the resolvers light-weight — essentially as mediators between the server framework and the data sources.</p><blockquote><strong>Side note<br></strong>The recommended way to access data sources is to pass them in the resolver’s context argument. However due to the <a href="https://github.com/nareshbhatia/graphql-bookstore/issues/2">open issue</a> with subscription workflows, I have chosen not to do so.</blockquote><p>The bookstore application has only one data source. Hence our dataSources object contains only one service — the bookService.</p><pre><strong>import </strong>{ BookService } <strong>from </strong>&#39;./book-service&#39;;<br><br><strong>export const </strong>dataSources = {<br>    bookService: <strong>new </strong>BookService()<br>};</pre><p>In the interest of simplicity, BookService implements an in-memory database. In a real application, this can be replaced by a more robust data solution such as MySQL, Postgres or MongoDB. The important part is that BookService methods return promises, so switching to a different data source should be easy.</p><p>Now that we understand the dataSources import, let’s focus on individual field resolvers. Again, there is a one-to-one mapping between fields and resolvers. Let’s start with the resolver for the authors field on type Query:</p><pre>authors() {<br>    <strong>return </strong>dataSources.bookService.getAuthors();<br>}</pre><p>This resolver simply fetches all the authors by calling the bookService and returns them. More formally, it returns a promise that resolves to an array of Authors.</p><p>Next let’s look at the resolver for the author query. This query receives an author id as the argument.</p><pre>author(parent, args) {<br>    <strong>return </strong>dataSources.bookService.getAuthor(args.id);<br>}</pre><p>Here we use the id argument sent to the query to get the author. The bookService returns the full author object, e.g. { id: &quot;eric-evans&quot;, name: &quot;Eric Evans&quot;}. This is important for the next few resolvers we will review.</p><p>Now let’s look at the resolver for the id field of an author:</p><pre>id(parent, args) {<br>    <strong>return </strong>parent.id;<br>}</pre><p>This is an easy one — it leverages the fact that the parent resolver in this case is the author resolver which returns the full Author object (see author resolver above). We simply pick up the id value from the parent argument and return it. In fact this is so easy that you can omit this resolver and the Apollo Server can figure it out. That’s why I have omitted it in the code base!</p><p>Ditto for the name resolver.</p><p>Finally, let’s look at the books resolver. This is an interesting one. books is not a property of the Author object. It’s a relation to books that the author has written. That’s why the author resolver did not return it. For this resolver we will have to send the author id to our data source and fetch the related books. That’s exactly what the code does:</p><pre>books(parent) {<br>    <strong>return </strong>dataSources<br>        .bookService.getAuthorBooks(parent.id);<br>}</pre><p>I hope this gives you a good feel of how to write resolvers. Now look at the publisher and book resolvers and see if they make sense.</p><h3>Summary</h3><p>We have now covered the full server implementation for queries. This is what we’ve learned:</p><ul><li>How to you use GraphQL Playground to send queries to the server</li><li>How to create and start and Apollo Server</li><li>How to merge type definitions into one cohesive schema</li><li>How to write resolvers</li></ul><p>Are you enjoying the series so far? I would love to get your questions and comments.</p><p>In part 3, we will implement a React client to go with our server.</p><h4><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Read Part 3: Queries (client implementation) &gt;</a></h4><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">GraphQL concepts I wish someone explained to me a year ago</a></p><h3>Resources</h3><ul><li><a href="https://www.prisma.io/blog/graphql-server-basics-the-schema-ac5e2950214e/">GraphQL Server Basics</a> on the Prisma blog: Excellent explanation of GraphQL schemas, type definitions and resolvers — a must read.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a55981f3a7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</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 I wish someone explained to me a year ago]]></title>
            <link>https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/514d5b3c0eab</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[apollo]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Thu, 20 Dec 2018 21:13:31 GMT</pubDate>
            <atom:updated>2018-12-28T19:40:26.429Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: GraphQL Basics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LH8SYJ7ANF2vpYBxaPnFPA.png" /><figcaption>Image by <a href="https://codepen.io/DianochkaMyQueen/pen/VdoGrz">Rostyslav</a></figcaption></figure><p>In a recent <a href="https://blog.npmjs.org/post/180868064080/this-year-in-javascript-2018-in-review-and-npms">blog article</a>, npm co-founder <a href="https://medium.com/u/42dbf8bc9177">Laurie Voss</a> commented:</p><blockquote>GraphQL, tracked by its most popular client library Apollo, continues to explode in popularity. We think it’s going to be a technical force to reckon with in 2019 … You’ll need to learn GraphQL.</blockquote><p>But learning is hard because most GraphQL tutorials use simplistic examples to teach its capabilities. When it comes to building real applications, we run into complexities that these tutorials do not address. In this series, we’ll look at GraphQL concepts using a realistic book domain that has 3 entities and 2 relationships. It’s usually the relationships that cause us heartburn, so we will tackle them head on.</p><ul><li><strong>Part 1: GraphQL Basics</strong></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Part 2: Queries (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-959b234ff430">Part 3: Queries (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-572d47318e17">Part 4: Mutations (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-61923646739b">Part 5: Mutations (client implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-62ec468b44ba">Part 6: Subscriptions (server implementation)</a></li><li><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-3b84203fb0b9">Part 7: Subscriptions (client implementation)</a></li></ul><p><em>One part will be released every day this week. </em><a href="https://twitter.com/NareshJBhatia"><em>Follow me</em></a><em> or </em><a href="https://contentupgrade.me/kKpZYZJj"><em>subscribe to my newsletter</em></a><em> to get updates on this series.</em></p><h3>Domain Model</h3><p>Let’s look at our book domain that has 3 entities and 2 relationships:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*30vyUpvNJrIWRE0vaoGnHg.png" /><figcaption>Book domain model</figcaption></figure><ul><li>Every book must have a publisher and a publisher may publish multiple books (one-to-many relationship).</li><li>A book may have one or more authors and an author may write many books (many-to-many relationship).</li></ul><p>Below is the front-end of our final application. It’s intentionally designed to show all the entities and relationships on a single page. This will allow us to demonstrate several GraphQL features — for example, how Apollo Cache normalizes entities to keep views consistent across the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTWVyppk7J2rskcGW8gGKA.png" /><figcaption>GraphQL Bookstore user interface</figcaption></figure><h3>What is GraphQL?</h3><p>GraphQL is a modern approach to access data from one or more data sources. <a href="https://facebook.github.io/graphql/">Open-sourced by Facebook in 2015</a>, it’s quickly gaining popularity over REST because of the ease with which you can access complex object graphs — hence the name <em>Graph Query Language</em>. However, don’t let the name fool you. In addition to querying, you can also change the data (a.k.a. <em>mutation</em>) and subscribe to data changes (a.k.a. <em>subscriptions</em>).</p><p>The GraphQL specification has been implemented in <a href="https://graphql.org/code/">many different programming languages</a>. We will be using a popular JavaScript implementation from <a href="https://www.apollographql.com/">Apollo</a>.</p><h3>Why GraphQL?</h3><h4>1. Access complex object graphs</h4><p>Real world data is complex — it contains a large number of objects connected via complex relationships. Just take a look at our simple bookstore example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDlKyThqaWUyWDwP7jl88A.png" /><figcaption>Bookstore object graph</figcaption></figure><p>Given this data, what kind of questions can we ask? Here’s a sample:</p><ul><li>What books have been published by <strong>Addison Wesley</strong>?</li><li>What books has <strong>Martin Fowler</strong> written and who has published them?</li><li>Who wrote <strong>Clean Code </strong>and what other books have they written?</li></ul><p>Note how we need to traverse the object graph in order to answer these questions. For the first question we need to start from a publisher and hop over to books. For the second question we need to start from an author, then hop over to books and finally to publishers. For the third question, we need to start with a book, then hop over to authors and finally to books again.</p><p>In the traditional REST world, each entity is associated with a separate endpoint (a.k.a. <em>resource</em>). We would have to hit multiple endpoints to satisfy our questions. Of course, we can cheat and include some related objects in our responses, but this approach will only take us so far. There will be future use cases that will need more and we will have to change our interfaces to accommodate for them. But what about a use case that needs less data? It either gets more data from our existing API or we create a new (nearly identical) API that returns less data. What a mess!</p><p>GraphQL changes all that — it hands over the control to the client. The server is only responsible for publishing the shape of the object graph (a.k.a. the <em>schema</em>) and then letting the client query it any way it wants. The resulting graph is returned to the client in one hit! For example, the third question above is satisfied by the following GraphQL query:</p><pre>{<br>  book(id: &quot;clean-code&quot;) {<br>    name<br>    authors {<br>      name<br>      books {<br>        name<br>      }<br>    }<br>  }<br>}</pre><p>This query literally says:</p><pre>Give me the book with id=&quot;clean-code&quot;<br>  Give me the book&#39;s name<br>  Give me the book&#39;s authors<br>    Give me the author&#39;s name<br>    Give me all the books the author has written<br>      Give me the book&#39;s name</pre><p>And the result of the query is self-explanatory:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;book&quot;: {<br>      &quot;name&quot;: &quot;Clean Code&quot;,<br>      &quot;authors&quot;: [<br>        {<br>          &quot;name&quot;: &quot;Robert C. Martin&quot;,<br>          &quot;books&quot;: [<br>            {<br>              &quot;name&quot;: &quot;Clean Code&quot;<br>            },<br>            {<br>              &quot;name&quot;: &quot;Agile Software Development&quot;<br>            }<br>          ]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>Note what is returned is a subset of the full object graph, but it is not returned as a graph — JSON can’t represent cyclic graphs. The server denormalizes the graph into a tree (with possibly duplicate nodes) and sends it over to the client as JSON. (Later we will see how Apollo client normalizes this tree back into a graph, removing duplicates and maintaining a single source of truth.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEvmjEa-wgLzP0kHjtmnoQ.png" /><figcaption>The query response is a tree representing a subset of the object graph</figcaption></figure><h4>2. Ask for what you need and get exactly that</h4><p>In the book query above, you may have noticed that we are asking for each entity field explicitly. This syntax is required and allows the client to ask for exactly what it needs and get only that — nothing more, nothing less. Imagine that the <em>Book</em> had 100 fields but our list view needed only 2: name and publication date. Then we could ask for just these two fields:</p><pre>{<br>  books {<br>    name<br>    publishDate<br>  }<br>}</pre><p>This approach improves the performance significantly, especially on mobile devices, where bandwidth and processing power are at a premium.</p><blockquote><strong>Side note<br></strong>There is a side effect of this design choice — you cannot treat received slices of your data as domain objects. If you have fetched a book from the server and saved it in a store, you cannot assume that all of its fields are available. All you have are simple groupings of primitive data types with no built-in behavior (see the <a href="https://www.martinfowler.com/bliki/AnemicDomainModel.html">Anemic Domain Model</a> anti-pattern).</blockquote><blockquote>Apollo’s <a href="https://www.apollographql.com/docs/react/advanced/caching.html">in-memory cache</a> does an amazing job of keeping the fields together in one place, but you still need to be aware that these are not true objects. Behavior must be introduced from the outside. I found <a href="https://medium.com/@__xuorig__/graphql-mutation-design-anemic-mutations-dd107ba70496">this article</a> by <a href="https://medium.com/u/ecb22831abfb">Marc-André Giroux</a> to be very helpful in designing operations that feel smart rather than anemic.</blockquote><blockquote>Moreover, don’t let all of this be an excuse to not understand your business domain. Your application should always be driven by a domain model and your domain objects (whether on the client or on the server) should always encapsulate behavior. You can read more about domain modeling in my <a href="https://archfirst.org/domain-driven-design/">Domain-Driven Design</a> article.</blockquote><h4>3. Keep client and server models in sync with type-safe schemas</h4><p>A major problem during application development is the conceptual disconnect between the client and the server. These two ends are generally developed by different teams at different speeds. In spite of careful documentation, it is common to get client and server data structures out of sync. This results in painful integration and bugs that go undetected even into production.</p><p>GraphQL helps this situation by offering an API-driven approach. Defining the API first establishes a common understanding between the client and the server. While this can be done with REST also, what is unique about GraphQL is its strong type system — expressed using a simple syntax called the GraphQL Schema Definition Language (SDL). Both the client and the server can validate their messages to conform to the schema, preventing a major category of bugs. Moreover we can generate parts of the client and the server from the schema, making it even more convenient to conform to the API.</p><h4>4. Access multiple data sources from a single endpoint</h4><p>As mentioned earlier, GraphQL provides access to data from one or more data sources. The client doesn’t care where the data physically resides. All it knows about is the logical model of the data (the schema). It is up to the server to fetch the data from one or more sources and stitch it together to conform to the schema. The diagram below shows some potential data sources such as files, databases, REST APIs, and content management systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*_VaONXPp3QKI6_-Pq51cVQ.png" /><figcaption>GraphQL provides a unified interface to access data from different sources</figcaption></figure><h4>5. Display changes in real-time</h4><p>There’s a whole range of applications that can benefit from displaying the latest data in real-time. For example, a trading application needs to show stock prices in real-time. Games and other interactive applications need to show events as soon as they happen.</p><p>GraphQL subscriptions are a way to push data from the server to the clients in real-time. As defined by the GraphQL specification: “subscription is a long‐lived request that fetches data in response to source events”. In fact, subscriptions are very similar to queries in that they specify a set of fields to be returned. However, instead of returning them immediately, the server sends them to the requesting client every time a specified event happens. For example, the subscription below specifies bookCreated as the <em>source event.</em> Whenever that event happens, the server pushes the book’s name to the client.</p><pre>subscription {<br>    bookCreated {<br>        book {<br>            name<br>        }<br>    }<br>}</pre><h3>Let’s write a schema</h3><p>Now that we understand the what and the why of GraphQL, let’s focus on the how. We’ll build the Bookstore application step-by-step. In this part, we’ll start by writing the Bookstore schema — remember our API-driven approach? In subsequent parts we will add features such as querying, mutations and subscriptions to create a full-fledged application.</p><p>Let’s start with a simple schema — enough to query the bookstore data. Just follow along right now to understand the concepts.</p><p>As a reminder, we’ll use the Book domain model (repeated below) to guide our schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*30vyUpvNJrIWRE0vaoGnHg.png" /><figcaption>Book domain model</figcaption></figure><p>Let’s start by defining the Author type:</p><pre><strong>type </strong>Author {<br>    id: ID!<br>    name: String!<br>    books: [Book!]!<br>}</pre><p>As mentioned earlier, GraphQL schemas are strongly typed. Here we see that the Author object has three fields:</p><ul><li>id: represents a unique identifier. Its type is ID, which is serialized in the same way as a String; however, it is not intended to be human‐readable. The exclamation mark at the end denotes that this field must be Non‐Null. (By default, all types in GraphQL are nullable.)</li><li>name: type String!, again Non-Null.</li><li>books: type [Book!]! — now that needs some explanation. Basically it says that books is an array of object type Book. The outer exclamation mark says that the array itself cannot be Null — at a minimum, it should be an empty array. The inner exclamation mark says that each entry in the array must be a Book — it cannot be Null. Note that this is a very “conceptual” definition of the books field — it says nothing about the underlying implementation, whether it is a foreign key in a relational table or an object reference in an object database — none of that! All it says is that given an author, we can get their authored books.</li></ul><p>So there you have it — our first GraphQL type declaration. You can read more about the GraphQL type system in the <a href="https://facebook.github.io/graphql/">official spec</a>. Don’t worry, it’s very readable!</p><p>Now that we have defined what an author is, let’s define a couple of queries — one to get all authors and another to get a specific author. Here you go:</p><pre><strong>type </strong>Query {<br>    authors: [Author!]!<br>    author(id: ID!): Author!<br>}</pre><p>To understand what this means, we must first understand two key concepts:</p><ul><li>GraphQL supports three types of operations — queries, mutations and subscriptions. What we have above is two query operations named authors and author. The first returns an array of authors and the second returns a single author.</li><li>A GraphQL schema defines a root operation type for each kind of operation. The Query wrapper around the two query operations above is the root operation type for queries. The other root operation types are type Mutation and type Subscription. Thus a typical GraphQL schema looks like this:</li></ul><pre><strong>type </strong>Query {<br>    ... query operations ...<br>}</pre><pre><strong>type</strong> Mutation {<br>    ... mutation operations ...<br>}</pre><pre><strong>type</strong> Subscription {<br>    ... subscription operations ...<br>}</pre><pre>... types referenced by the above root operations ...</pre><p>Now that we understand all this, let’s write out the complete schema for the bookstore (just for queries of course):</p><pre><strong>type </strong>Query {<br>    authors: [Author!]!<br>    author(id: ID!): Author!<br>    publishers: [Publisher!]!<br>    publisher(id: ID!): Publisher!<br>    books: [Book!]!<br>    book(id: ID!): Book!<br>}</pre><pre><strong>type </strong>Author {<br>    id: ID!<br>    name: String!<br>    books: [Book!]!<br>}<br><br><strong>type </strong>Publisher {<br>    id: ID!<br>    name: String!<br>    books: [Book!]!<br>}<br><br><strong>type </strong>Book {<br>    id: ID!<br>    name: String!<br>    publisher: Publisher!<br>    authors: [Author!]!<br>}</pre><p>That’s it! This is a complete and valid schema that defines 6 query operations on our bookstore.</p><p>However, there is a catch — As our application grows, we will need to add more types and operations to the schema. At some point, this schema will become unwieldy to manage in a single file. We need to modularize it, just like we modularize code into modules and our UI into components. The easiest way to do this is to split the schema into smaller manageable chunks. We will break up our schema on entity boundaries. Let’s create three files, one for each entity. By convention, we use .graphql as the extension for these files.</p><pre># ----- author.graphql -----<br><strong>type </strong>Author {<br>    id: ID!<br>    name: String!<br>    books: [Book!]!<br>}<br><br><strong>type </strong>Query {<br>    authors: [Author!]!<br>    author(id: ID!): Author!<br>}</pre><pre># ----- publisher.graphql -----<br><strong>type </strong>Publisher {<br>    id: ID!<br>    name: String!<br>    books: [Book!]!<br>}<br><br><strong>type </strong>Query {<br>    publishers: [Publisher!]!<br>    publisher(id: ID!): Publisher!<br>}</pre><pre># ----- book.graphql -----<br><strong>type </strong>Book {<br>    id: ID!<br>    name: String!<br>    publisher: Publisher!<br>    authors: [Author!]!<br>}<br><br><strong>type </strong>Query {<br>    books: [Book!]!<br>    book(id: ID!): Book!<br>}</pre><p>Now that’s more scalable! In the next part, we’ll merge these schemas into one using a library called <a href="https://github.com/okgrow/merge-graphql-schemas">merge-graphql-schemas</a>.</p><h3>Source Code</h3><p>The source code for this series is available in the <a href="https://github.com/nareshbhatia/graphql-bookstore">graphql-bookstore</a> repo on GitHub. I have marked the code for each part with a git tag. This should make it easier to understand the code for the part that you are reading — without distractions from the later stuff. To look at the code for part 1, execute the following commands on your command line:</p><pre>git clone <a href="https://github.com/nareshbhatia/graphql-bookstore.git">https://github.com/nareshbhatia/graphql-bookstore.git</a><br>cd graphql-bookstore<br>git checkout 1-basics</pre><p>The GraphQL schema discussed in this part is saved under apollo-bookstore-server/src/graphql/typedefs.</p><h3>Summary</h3><p>We have now covered the basics of GraphQL — what is it and its benefits. We also looked at how to compose a GraphQL schema.</p><p>I realize that this was a long read, but hopefully it gave you a strong foundation before jumping into implementation. I would love to get your questions and comments.</p><p>In part 2, we will use our bookstore schema to build a GraphQL server. Until then, happy computing!</p><h4><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">Read Part 2: Queries (server implementation) &gt;</a></h4><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-6a55981f3a7e">GraphQL concepts I wish someone explained to me a year ago</a></p><h3>Resources</h3><ul><li><a href="https://facebook.github.io/graphql/">The GraphQL specification</a></li><li><a href="https://blog.apollographql.com/the-concepts-of-graphql-bc68bd819be3">GraphQL Concepts Visualized</a> by <a href="https://medium.com/u/c066cfeacf95">Dhaivat Pandya</a>: Great explanation of the GraphQL mental model using diagrams.</li><li><a href="https://philsturgeon.uk/api/2017/01/24/graphql-vs-rest-overview/">GraphQL vs REST</a> by <a href="https://medium.com/u/63d3c9a9b3be">Phil Sturgeon</a>: Objective and thoughtful comparison of GraphQL and REST.</li><li><a href="https://blog.apollographql.com/graphql-schema-design-building-evolvable-schemas-1501f3c59ed5">GraphQL Schema Design</a> by <a href="https://medium.com/u/ecb22831abfb">Marc-André Giroux</a>: Explains best practices to to avoid breaking changes in your schema.</li><li><a href="https://medium.com/@__xuorig__/graphql-mutation-design-anemic-mutations-dd107ba70496">GraphQL Mutation Design</a> by <a href="https://medium.com/u/ecb22831abfb">Marc-André Giroux</a>: Explains how to design mutation APIs that don’t feel anemic.</li><li><a href="https://www.apollographql.com/docs/tutorial/introduction.html">Apollo Fullstack Tutorial</a>: Another take on explaining GraphQL, right from the Apollo team. At the time of this writing, it covers queries and mutations only. Worth a read.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=514d5b3c0eab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/graphql-concepts-i-wish-someone-explained-to-me-a-year-ago-514d5b3c0eab">GraphQL concepts I wish someone explained to me a year ago</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing UI Components with Lerna and Yarn Workspaces]]></title>
            <link>https://medium.com/naresh-bhatia/sharing-ui-components-with-lerna-and-yarn-workspaces-be1ebca06efe?source=rss----4814260e8609---4</link>
            <guid isPermaLink="false">https://medium.com/p/be1ebca06efe</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[yarn-workspace]]></category>
            <category><![CDATA[lerna]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Naresh Bhatia]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 20:49:26 GMT</pubDate>
            <atom:updated>2018-12-17T21:34:37.793Z</atom:updated>
            <content:encoded><![CDATA[<p>Today’s popular front-end frameworks like Angular and React allow us to create rich web applications using modular, reusable components. Most of the time we get away with reusing components that someone else wrote. <a href="https://material.angular.io/">Angular Material</a>, <a href="https://material-ui.com/">Material-UI</a> and <a href="https://glamorous.rocks/">Glamorous</a> are just a few examples of the many off-the-shelf component libraries that allow us to build rich web applications with minimal effort. We generally don’t think about writing shared reusable components until we have to write moderately complex applications. In my case, our team was tasked to write a set of reusable components so that they can be used to quickly compose a suite of complex financial applications. I started thinking about the best way to create these components.</p><h3>Motivation: Faster Development Cycle</h3><p>Imagine that you were writing an online shopping app. There’s a page in this app that shows the list of orders. The OrderList component uses the List component from the Material-UI library. Your component hierarchy might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*bsoC1YH46A_7fFz0Oadpqg.png" /></figure><p>Let’s see how these components may be organized in your repo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpW9Hg0WfaT5gLOshN9luQ.png" /></figure><p>Your repo has a src folder that contains the code you wrote. You also have a node_modules folder that contains reusable components installed from npm.</p><p>Now imagine that you needed to package OrderList as a independent component that could be reused across several applications. How might you do that? Here’s one way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaSW_DHtaT42_-JZ6yySYQ.png" /></figure><p>We have created a new repo called myshared. This repo contains the OrderList component along with its dependencies — in this case the List component from Material-UI. We have published the myshared repo to npm and installed it in myapp. This allows us to use OrderList in myapp and any other app. Yeah! But do you see an issue with this approach?</p><p>Of course! For every change in OrderList, we must publish myshared to npm and reinstall it in myapp. This is extremely frustrating. How can we speed this up?</p><blockquote>Note that I have glossed over an important step — before publishing to npm, we should unit test our component to make sure it works as expected. We could use testing frameworks such as <a href="https://facebook.github.io/jest/">Jest</a> or <a href="https://jasmine.github.io/">Jasmine</a> to do this. We could also use Storybook to visualize different states of our component and develop it interactively.</blockquote><h3>Lerna and Workspaces - Package Management Made Easy</h3><p><a href="https://lernajs.io/">Lerna</a> and <a href="https://yarnpkg.com/lang/en/docs/workspaces/">Yarn Workspaces</a> give us the ability to build libraries and apps in a single repo (a.k.a. monorepo) without forcing us to publish to npm or other registries. We can go through code-test-debug cycles much faster by sharing components locally. Of course, we still have the option of publishing to npm at any time. Let’s see how this works.</p><p>Lerna &amp; Yarn Workspaces expect a folder called packages in your repo. A package is simply a “mini-repo” that can be versioned, built and published independently. The monorepo shown in the diagram below has two packages</p><ul><li><strong><em>myshared</em></strong>: this is a library of reusable components</li><li><strong><em>myapp</em></strong>: an app that uses the components in <em>myshared</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4AdwaCWGqRq88-a4dcDNw.png" /></figure><p>We can have any number of packages inside a monorepo, with complex dependencies between each other. The secret sauce behind managing these dependencies is the concept of <em>symlinks</em>. In computing, a symlink (short for Symbolic Link) is a file that references another file or directory and makes it look like the referenced file or directory is at the original file’s location. Looking at the diagram above, there is a symlink called <em>myshared</em> under myapp/node_modules that references the myshared package under packages. The beauty behind Lerna and Yarn Workspaces is that these tools can find package dependencies by analyzing the package.json files under each package. After determining these dependencies, they create symlinks that make each package think that their dependencies have been installed under their own node-modules folder! Once these links are established, we can build any package without publishing dependent packages to a registry. This is pretty neat!</p><p>Now you may be thinking, why do we need both Lerna and Yarn Workspaces? What roles do they each play in this workflow? Quite frankly, there is a big overlap between the functionalities offered by the two tools. Both are able to analyze package.json files and create the necessary symlinks. However, Lerna falls short in some important use cases — as I found out <a href="https://github.com/nareshbhatia/react-multiple-copies-issue">the hard way</a>. Turns out that libraries like React and MobX get very upset if an app loads multiple copies of these libraries (see <a href="https://reactjs.org/warnings/refs-must-have-owner.html">this React warning</a> and <a href="https://github.com/mobxjs/mobx/issues/1082">this MobX issue</a> for details). Unfortunately, Lerna does exactly that even if we carefully specifying dependencies, dev dependencies and peer dependencies. On the other hand, Yarn Workspaces has mastered this task. It automatically detects such dependencies and includes the libraries only once in the final app. It’s the best tool I know to manage package dependencies in a monorepo.</p><p>So what purpose does Lerna serve? Well, Lerna provides the high-level commands to optimize the management of multiple packages. For example, with one Lerna command you can iterate through all the packages, running a series of operations (such as linting, testing and building) on each package. It compliments Yarn Workspaces in managing your monorepo.</p><h3>Let’s give it a spin</h3><p>Now that we understand what Lerna and Yarn Workspaces do, let’s try them out first-hand. I will make it easy for you — just clone my <a href="https://github.com/nareshbhatia/lerna-workspaces-concepts">sample repo</a> from Github. This repo contains vanilla JavaScript code, no fancy React or Angular components, but it is enough to understand the fundamentals. We have two packages:</p><ul><li><strong><em>temp-utils</em></strong>: a package containing temperature conversion utilities. This package has an external dependency on lodash (you can see this in the package.json file).</li><li><strong><em>weather-app</em></strong>: a command-line app that uses the temp-utils package (as specified in its package.json file).</li></ul><p>The key to setting up Lerna and Yarn Workspaces is the lerna.json configuration file in the root directory:</p><pre>{<br>  &quot;lerna&quot;: &quot;2.11.0&quot;,<br>  &quot;packages&quot;: [<br>    &quot;packages/*&quot;<br>  ],<br>  &quot;version&quot;: &quot;independent&quot;,<br>  &quot;npmClient&quot;: &quot;yarn&quot;,<br>  &quot;useWorkspaces&quot;: true<br>}</pre><p>The configuration basically tells Lerna to use independent versions for each package and to enable integration with Yarn Workspaces. That’s it! We are now ready to roll. Open a command line shell and set you directory to the root of the monorepo. Run the following command:</p><pre>$ yarn</pre><p>This allows yarn to analyze all the packages in your monorepo. It will download external dependencies (like lodash) from npm and create symlinks for internal dependencies. You will notice that yarn does not create node_modules directories in either of your packages — this is not the usual case. For this repo, Yarn has <em>hoisted</em> all the dependencies to its root. If you look inside lerna-workspaces-concepts/node_modules you will find the symlink to temp-utils.</p><p>Now that Yarn has prepared the repository with symlinks, you can build the temp-utils library and the weather-app, all in one shot — thanks to Lerna! Execute the following command in the root directory:</p><pre>$ yarn build</pre><p>This command effectively runs the following Lerna command (see package.json). The Lerna command compiles the source folder in all packages using babel.</p><pre>$ lerna exec -- babel src -d dist --ignore test.js</pre><p>Notice how Lerna saved you time by going through each package and building it for you. No need to do this manually! Now you are ready to run your final app. Execute the following command:</p><pre>$ yarn start</pre><p>This effectively runs</p><pre>$ node packages/weather-app/dist/weather-app</pre><p>You should see the following output:</p><pre>100 degrees C = 212 degrees F<br>212 degrees F = 100 degrees C<br>average of [10, 20, 30] = 20</pre><p>This simple example shows the power of Lerna and Yarn Workspaces.</p><h3>Starter Templates</h3><p>Now that you understand the basics of Lerna and Yarn Workspaces, you should be able to create more complex monorepos to build reusable UI libraries and apps. Kick-start your monorepo using one of these starter templates:</p><ol><li><a href="https://github.com/nareshbhatia/lerna-workspaces-react-es6">React ES6 template</a></li><li><a href="https://github.com/nareshbhatia/lerna-workspaces-react-ts">React TypeScript template</a></li><li><a href="https://github.com/nareshbhatia/react-mobx-mui-ts-monorepo">React, MobX, Material-UI Monorepo</a> using TypeScript</li></ol><h3>TL;DR</h3><p>Lerna and Yarn Workspaces give us the ability to build libraries and apps in a single repo without forcing us to publish to npm or other registries. We can go through code-test-debug cycles much faster by sharing components locally.</p><p>Yarn Workspaces finds package dependencies by analyzing the package.json files under each package and creates symlinks to satisfy internal dependencies.</p><p>Lerna provides high-level commands to optimize the management of multiple packages.</p><p>Lerna and Yarn Workspaces together improve the developer experience of managing multiple packages in a monorepo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj&amp;src=https%3A%2F%2Fcontentupgrade.me%2FkKpZYZJj.html%3Fref%3D&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=contentupgrade" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href">https://medium.com/media/2cfd4363dd5db96f86898134a2c3fa5b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1ebca06efe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naresh-bhatia/sharing-ui-components-with-lerna-and-yarn-workspaces-be1ebca06efe">Sharing UI Components with Lerna and Yarn Workspaces</a> was originally published in <a href="https://medium.com/naresh-bhatia">Naresh Bhatia</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>