<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David He on Medium]]></title>
        <description><![CDATA[Stories by David He on Medium]]></description>
        <link>https://medium.com/@jialhe85?source=rss-b498ae8d18e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A2HPsGd6ITTH_yMDHK6AAg.jpeg</url>
            <title>Stories by David He on Medium</title>
            <link>https://medium.com/@jialhe85?source=rss-b498ae8d18e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:47:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jialhe85/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Serverless alias insight]]></title>
            <link>https://medium.com/swlh/serverless-alias-insight-e1db93a69562?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1db93a69562</guid>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Sat, 14 Mar 2020 00:10:06 GMT</pubDate>
            <atom:updated>2020-11-04T22:04:25.746Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://serverless.com/">Serverless framework</a> offers us the capability of creating different environments for deployments via stage. We can create <strong>dev, test, uat </strong>and <strong>prod </strong>environments by just supplying these values to stage parameter and Serverless will do the heavy lifting jobs for us. Environments are isolated from each other meaning changes that’s made to one will not affect the other. Brilliant!</p><p>This is really a great feature right? Yes but not good enough. Why? Because it does not actually take advantage of a powerful feature lambda has out-of-box. That is lambda version and alias.</p><h3>The problem with stage</h3><p>Think about this, after days of hard work, you have your first APIG + lambda app deployed and frontend devs are happy and start using the api. Now you are given a new task to remove an existing api in favour of a new one that has different path and payload. The change itself is easy and you have it done on a feature branch in the half day. Once done, you want to push it out for yourself to play with first before others can use it.</p><p>This scenario is very common in our day-to-day development. Apparently, you could use stage again and supply the feature branch’s name to it resulting in another CloudFormation stack, another APIG, another lambda etc. Nothing harms, it gets job done and the new staged environment stands independently from the previous release.</p><p>Have you spot the problem? Yes, a new lambda and APIG are created! You might wonder what is wrong with this? While, it is ok to have one more lambda or APIG to manage, but ideally what you want to do is keep only one lambda and one APIG while still being able to maintain different versions. The key is — Lambda alias + APIG stage.</p><p>It’s not obvious as to how you can enable them in your app though.</p><h3>Serverless-aws-alias plugin comes to the rescue</h3><p>This <a href="https://github.com/serverless-heaven/serverless-aws-alias">plugin</a> does the job perfectly! But you might be in the same boat as me when reading their docs that explains how they make multi-branch deployment environment possible. I am getting myself lost in a pile of terms — Serverless stage, API stage, Serverless alias, lambda alias and lambda version.</p><p>If you are the one please keep reading on since I will give you an insight into how these work together to achieve multiple environments while keeping minimal manageable resources.</p><h3>Concepts</h3><p>Let me quickly run you through them:</p><p><strong>Lambda version</strong> — Version identifier to your lambda. $LATEST points to the latest version. Serverless automatically creates an incremental version starting with 1 every time you deploy your lambda. i.e The second time you push your lambda, version will be 2 and $LATEST points to 2. In other words, 2 and $LATEST are the same.</p><p><strong>Lambda alias</strong> — An alias is like a pointer that points to a specific lambda version.</p><p><strong>APIG stage — </strong>Same concept as Lambda version but without $LATEST identifier. It sticks to Serverless stage unless you deploy with alias via alias plugin. That will set stage equally to alias. A stage can be linked to a lambda alias.</p><p><strong>Serverless stage </strong>— Serverless way of identifying infrastructure for different deployment environments.</p><p>With these concepts clarified, let me show you how Serverless creates isolated infrastructure and alias plugin play its part in enabling lambda alias feature.</p><h3>Show me your example</h3><p>Below is the example <strong>serverless.yml</strong> I will use throughout this demo.</p><pre>service:<br>  name: serverless-alias-insight</pre><pre># plugins:<br>#   - serverless-aws-alias</pre><pre>frameworkVersion: &quot;&gt;=1.1.0 &lt;2.0.0&quot;</pre><pre>provider:<br>  name: aws<br>  runtime: nodejs10.x<br>  stage: test<br>  profile: qq<br>  region: ap-southeast-2</pre><pre>functions:<br>  HelloWorld:<br>    handler: handler.endpoint<br>    events:<br>      - http:<br>          path: ping<br>          method: get</pre><p>It’s as simple as an APIG + Lambda stack. Note I set stage to <strong>test</strong>. I also leave handler part out of picture as it serves no purpose to our demo.</p><p>There are 2 main circumstances we will need to consider:</p><ol><li>No alias plugin</li><li>With alias plugin</li></ol><h3>No alias plugin</h3><p>Start without alias plugin, When deploying, Serverless provisions the following main resources on your behalf:</p><ul><li>serverless-alias-insight-<strong>test</strong>-HelloWorld — lambda</li><li><strong>test</strong>-serverless-alias-insight — APIG</li><li>serverless-alias-insight-<strong>test — </strong>CloudfFormation</li></ul><p>As you can see, Serverless uses stage to name our resources. If you leave stage unset, it will default to dev. When another deploy occurs, Serverless will create a separate stack dev holding duplicate resources under it. It is unnecessary and we would have saved it if alias plugin was used.</p><h3>With alias plugin</h3><p>Next, let’s see how alias can help us with resources isolation without duplicates.</p><p>Uncomment the line below to activate the plugin:</p><pre>plugins:<br>  - serverless-aws-alias</pre><p>Deploy your app again and see what comes out this time:</p><ul><li>serverless-alias-insight-<strong>test</strong>-<strong>test — </strong>CloudFormation</li><li>An alias version of lambda</li><li>A new APIG stage <strong>test</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*H-uTK1kTZ2592JLfOnN8fA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*-2BhutbfQZGVNJhyXC4T0A.png" /></figure><p>Awesome! We have lambda alias/version enabled within the same one lambda. Besides, it also created an alias version of CloudFormation stack to your main one.</p><p>In summary, Serverless created aliased resources using stage as alias.</p><p>Lastly, it’s time to unlock the true power of alias plugin — deploy with alias flag!</p><h3><strong>Deploy using alias flag</strong></h3><p>Alias plugin allows you specify alias through CLI and if it’s left undetermined, it will use stage as its value.</p><pre>serverless deploy --alias &lt;YOUR_ALIAS&gt;</pre><p>What I like to do is use my feature branch as alias. That way my isolated environments will have branch in their names.</p><p>For instance, if I want to create a new delete API endpoint on a branch called add-delete-api, what I can do is:</p><pre>serverless deploy --alias add-delete-api</pre><p>Doing this will create separate CloudFormation Stack, a new API stage and a lambda alias both named after add-delete-api. So no duplicate lambdas anymore. I can simply switch my endpoint to aliased version to test delete functionality.</p><pre><a href="https://muwlrnx5s8.execute-api.ap-southeast-2.amazonaws.com/dragon">https://xxxxxxx.execute-api.ap-southeast-2.amazonaws.com/</a>add-delete-api</pre><p>This endpoint is associated with my aliased version of lambda below:</p><pre>arn:aws:lambda:ap-southeast-2:xxxxxxxxx:function:serverless-alias-insight-test-HelloWorld:add-delete-api</pre><h3><strong>Heads-up</strong></h3><p>Be aware aliased version of your resources will remain there unless you manually remove them:</p><pre>serverless alias remove --alias=MY_ALIAS</pre><p>If you need to remove your Serverless function, you have to remember that all aliased versions need to be removed before you can get rid of the main stack.</p><p>To make your life easier, what you could do is hook up alias removal to merge event of your feature branch PR. As thus, your aliased version will be removed and you don’t need to worry about dangling ones which require clean-up later down the track.</p><h3>Bonus: Use alias plugin in CI/CD</h3><p>During CI/CD process, you can retrieve the feature branch name and feed it to alias flag that will dynamically create aliased version of resources for you.</p><h3><strong>The end</strong></h3><p>I hope this article explains confusing concepts well and helps you create and manage different environments elegantly.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1db93a69562" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/serverless-alias-insight-e1db93a69562">Serverless alias insight</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A slick way of playing with Jenkins pipeline]]></title>
            <link>https://codeburst.io/a-slick-way-of-playing-with-jenkins-pipeline-b173173bac5c?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b173173bac5c</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[local]]></category>
            <category><![CDATA[jenkinsfile]]></category>
            <category><![CDATA[jenkins-pipeline]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 10:36:17 GMT</pubDate>
            <atom:updated>2020-02-06T04:49:07.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*8WSOIMQh__rkmb1019IHNg.jpeg" /><figcaption>Stay strong like Jenkins</figcaption></figure><p>I’ve recently decided to ease myself into DevOps and move away from full-stack engineer. To be honest, I’ve found it a lot more fun than being a developer. It’s a completely different world and joyful journey. I might seek sometime down the path to write an article to tell you guys more about my DevOps story but today I will present you something technical 😉.</p><p>I like trying it out when I am introduced to a new technology. i.e Python I will start writing dozens if not hundreds of lines of code and log result to the console at different places to get myself around how built-in functions, constructs and more work. Same with Jenkins, I begin with thinking if there is a way to run it locally on my machine to experiment its rich features without the requirement to create and configure a remote GitHub Repo and seeing build results by pushing code up. After some investigation, I’ve tracked down the way. Let me show you how.</p><p><strong><em>Note: I won’t cover how to run a Jenkins on your local machine. Several ways including run it in a docker container or run a jenkins war (I used this one for the demo) can be found on the internet. Go and pick an approach of your choice and make sure you have a fresh Jenkins server running locally before reading on.</em></strong></p><p><strong><em>For those choose Jenkins war file, run the command below to start your Jenkins server up:</em></strong></p><p><em>JENKINS_HOME=~/lab/jenkins java -jar jenkins.war</em></p><p><strong><em>If run it in a docker container, volume mount needs to be configured correctly or file-protocol based url will point to filesystem inside the container not on the host.</em></strong></p><h3>Create an app and a Jenkinsfile</h3><ol><li>Create a new directory <strong>app</strong> from which you add a Jenkins file</li></ol><pre>pipeline {<br>    agent any<br>    stages {<br>        stage(&#39;build&#39;) {<br>            steps {<br>                echo &quot;Hello World!&quot;<br>            }<br>        }<br>    }<br>}</pre><p>2. Run git init to enable git in your app</p><p>Now let’s get our hands dirty on Jenkins side.</p><h3>Setup a new pipeline</h3><ol><li>Choose Pipeline from the list and give it a name. I use test.</li><li>Choose <strong>GitHub</strong> project under <strong>General, </strong>copy and paste the absolute path to your app in the box of<strong> Project url. </strong>See my input as an example:<strong><br></strong><em>file:///Users/David/app/</em></li><li>Choose <strong>Trigger builds remotely </strong>under<strong> Build Triggers</strong>. type in a token in <strong>Authentication Token</strong> filed. For this demo, I use david.</li><li>Under <strong>Pipeline</strong> section, select Pipeline script from SCM from <strong>Definition</strong> dropdown list. Pick <strong>Git</strong> as <strong>SCM</strong>. For <strong>Repository URL</strong>, make it the same as <strong>Project url</strong> specified in step 2.</li><li>Leave all else as is and hit save.</li></ol><h3>Configure an user with proper permissions</h3><p>Basically, we need to grant a particular user with proper permissions for this practice to happen.</p><ul><li>Overall Read</li><li>Job Build, Read, Workspace</li></ul><p>For the sake of learning purpose, I select <strong>Logged-in users can do anything option </strong>under <strong>Manage Jenkins</strong> &gt; <strong>Configure Global Security</strong>. If you situation is different to mine, ensure you configure a user with permissions as mentioned above.</p><h3>Add API Token for the user</h3><p>API token is needed to trigger a build from calling a particular url.</p><p>Go to <strong>Manage Jenkins</strong> &gt; <strong>Manage Users</strong> &gt; choose the right user from list &gt; <strong>Configure.</strong></p><p>In <strong>API Token </strong>section, type in user name in the field and hit <strong>Add new Token. </strong>This will generate a random hash that you need to note down for later use.</p><p>Up until now, you have done Jenkins part. There is still one more piece to get before completing the full puzzle.</p><h3>Add git post commit hook</h3><p>Once again, switch to your app directory and go to .git/hooks and drop a file named post-commit in there with contents below:</p><pre>#!/bin/sh</pre><pre>curl -X POST http://david:&lt;API_TOKEN&gt;@localhost:&lt;JENKINS_SERVER_PORT&gt;/job/test/build?token=&lt;AUTHENTICATION_TOKEN&gt;</pre><p>In my case, full url is:</p><pre>curl -X POST <a href="http://david:11be2af696ed95c021ae0e022777a7dfed@localhost:8080/job/test/build?token=david">http://david:11be2af696ed95c021ae0e022777a7dfed@localhost:8080/job/test/build?token=david</a></pre><p>Lastly, don’t forget to make it executable by running chmod +x post-commit.</p><p>Congratulazioni!! you can now add and commit your Jenkins file, sit back and watch build being triggered automatically.</p><p>Thanks for reading😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b173173bac5c" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/a-slick-way-of-playing-with-jenkins-pipeline-b173173bac5c">A slick way of playing with Jenkins pipeline</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing tips for ApolloClient with React]]></title>
            <link>https://medium.com/swlh/testing-tips-for-apolloclient-with-react-b58373eebb96?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58373eebb96</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 13:51:58 GMT</pubDate>
            <atom:updated>2019-08-29T14:05:26.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iP68WCHhHjx5ieFQ" /><figcaption>Photo by <a href="https://unsplash.com/@_louisreed?utm_source=medium&amp;utm_medium=referral">Louis Reed</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently participate in writing tests to cover my react components powered by Apollo Client with hooks. Follow by <a href="https://www.apollographql.com/docs/react/recipes/testing/">examples</a> on Apollo Client official docs, it looks very straightforward and I thought could have job done fairly quickly but I’ve successfully proved myself wrong since it took me way more time than expected. The reason being is investigating and fixing errors/warnings I ran into while writing tests took me plenty of time.</p><p>In this write-up, I will share serval useful tips I’ve reaped in order for other developers to quickly spot the issue and fix it in no time!</p><p>Thanks to discussions around issues library maintainers and community users have on Apollo Client GitHub, their comments are really helpful to me in terms of thorough understanding of issues and coming up with right fixes.</p><h3>1. Query in test and in component must match.</h3><p>Non-identical queries in these two places will result in error below:</p><blockquote>Network error: No more mocked responses for the query</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9317f1c4e8318ca32eb98a0b1a67a71f/href">https://medium.com/media/9317f1c4e8318ca32eb98a0b1a67a71f/href</a></iframe><p>If 2 ids are evaluated to 2 different values i.e match.params.id is undefined, such error will emerge and stand in your way.</p><p>I am using react-router so I need to simulate the case where url matches route path that is bound to my testing component with path parameter idequal to 1abc.</p><h3>2. Include __typename to all object types when you have fragments/unions in your query.</h3><p>Don’t be fooled by simplified <a href="https://www.apollographql.com/docs/react/recipes/testing/#mockedprovider">example</a> sourced from <a href="https://www.apollographql.com/docs/react/recipes/testing/">Testing React Components</a>. In that example, you don’t see __typename embedded in the mocks. While it is not required with simple query that is free of fragments/unions on object type, unfortunately you need to have them if your query looks like this:</p><pre>export const ViewMiniAppQuery = gql`<br>  query ViewMiniAppQuery($id: ID!, $version: String) {<br>    app(id: $id, version: $version) {<br>      ...ViewMiniApp<br>      versions {<br>        ...ViewMiniApp<br>      }<br>    }<br>  }<br>  ${ViewMiniAppFragment}<br>`;</pre><p>Failing to do so is likely to result in error below:</p><blockquote>Network error: Error writing result to store for query:</blockquote><p>To fix it, you need to:</p><ol><li>Leave addTypename out of picture when configuring MockProvider. This will add this extra field to query object for the sake of caching.</li><li>Make sure mocked query result has __typename in involving object type.</li></ol><pre>// wrong<br>{<br>  id: &#39;1abc&#39;,<br>  name: &#39;customer-search&#39;,<br>  events: {<br>    id: &#39;eve1&#39;,<br>    value: &#39;event1&#39;,<br>  }<br>}</pre><pre>// right<br>{<br>  id: &#39;1abc&#39;,<br>  name: &#39;customer-search&#39;,<br>  __typename: &#39;MiniApp&#39;,<br>  events: {<br>    id: &#39;eve1&#39;,<br>    value: &#39;event1&#39;,<br>    __typename: &#39;Events&#39;<br>  }<br>}</pre><h3>3. Use IntrospectionFragmentMatcher when you have fragments/unions in your query.</h3><p>Likewise, you need to replace the default <strong>heuristic fragment matcher</strong> with IntrospectionFragmentMatcher since Apollo Client needs more information to work out your spread operator applies to a fragment type rather than regular object type:</p><pre>query {<br>  all_people {<br>    ... on Character {<br>      name<br>    }<br>    ... on Jedi {<br>      side<br>    }<br>    ... on Droid {<br>      model<br>    }<br>  }<br>}</pre><pre>// schema<br>interface Character {<br>  id: ID!<br>  name: String!<br>  friends: [Character]<br>  appearsIn: [Episode]!<br>}</pre><pre>type Human implements Character {<br>  id: ID!<br>  name: String!<br>  friends: [Character]<br>  appearsIn: [Episode]!<br>  starships: [Starship]<br>  totalCredits: Int<br>}<br><br>type Droid implements Character {<br>  id: ID!<br>  name: String!<br>  friends: [Character]<br>  appearsIn: [Episode]!<br>  primaryFunction: String<br>}</pre><p>In this example, Character is actually an interface but Apollo Client has no way of knowing it without little help from introspective schema. If we use default fragment matcher, we might be given unexpected errors.</p><p>Refer to <a href="https://www.apollographql.com/docs/react/advanced/fragments/#fragments-on-unions-and-interfaces">Fragments on unions and interfaces</a> for how to setup IntrospectionFragmentMatcher.</p><h3>4. Separate Cache for each individual test case.</h3><p>When dealing with mutations, you need to create and set cache to MockProvider. The tip here is re-create a new cache instance for each run of your test case. Puzzling cached data will be in the memory if you don’t follow this rule:</p><pre>beforeEach(() =&gt; {<br>  cache = new InMemoryCache({ fragmentMatcher });<br>});</pre><p>This procedure enables a fresh cache to be created each time a new test case is run.</p><h3><strong>More tips to come… Stay tuned!😎</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EIUnIHHuMTPd-W1r" /><figcaption>Photo by <a href="https://unsplash.com/@timotheus_froebel?utm_source=medium&amp;utm_medium=referral">Timotheus Fröbel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58373eebb96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/testing-tips-for-apolloclient-with-react-b58373eebb96">Testing tips for ApolloClient with React</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My journey to make styling with Material-UI right]]></title>
            <link>https://codeburst.io/my-journey-to-make-styling-with-material-ui-right-6a44f7c68113?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a44f7c68113</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[styling]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Tue, 04 Jun 2019 23:12:41 GMT</pubDate>
            <atom:updated>2019-06-10T23:28:03.798Z</atom:updated>
            <content:encoded><![CDATA[<h3>My journey to making styling with Material-UI right</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*7LOWVelUHYS1iqeX34Whzg.png" /></figure><p>Material-UI is a React-based UI libraries that implement <a href="https://material.io/design/introduction/#principles">Google Material Design</a>. It’s very popular among other great UI libraries such as Semantic-UI-React and React Bootstrap.</p><p>The real power of Material-UI (will call it MU for short from now on) lies in its flexibilities. What I mean by this is they provide a whole bunch of different options of getting your job done. For example, basically, you are given 3 different ways to style your components.</p><ul><li>Use hook-based api (makeStyles/useStyles)</li><li>Use styled-components api (styled(Component)({…stylesObject})</li><li>Use HoC (withStyles(styles)(Component)</li></ul><p>Multiple options guarantee you will always find the most appropriate way to style your components with ease.</p><p>In this post, I am not gonna discuss where and how you should use each of these apis but walk you through the process for component styling. The official doc lacks the step-by-step guide as to how you should style complex components like TextField which is composed of children components/elements.</p><p>To illustrate, I will choose to use &lt;TextField&gt; as an example and cover how you can style it based on its different states — focused, hover etc.</p><p>Let’s start!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*DWrQ4etWHEkCtk1JYSf5XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*WocOXps9Y3Mr4EVDyUA6GA.png" /><figcaption>TextField with outlined as variant</figcaption></figure><p>The above screenshots show how an outlined textfield look like when being rendered in different states — initial state and focused. Now make some changes to its styles:</p><ul><li>Make border red when it’s being hovered over</li><li>Make border green when users start typing — focused</li></ul><p>You might wonder isn’t it as simple as create styles with a class name and apply it to the component by using className property since every MU component accepts this property to allow styles overwriting? Well, the answer is yes and no. For some simple components that does not have much constitutional React elements we can use className. For TextField in our example, className will not help. Let me show you what happens when using className.</p><pre>const useStyles = makeStyles(theme =&gt; ({<br>  textField: {<br>    marginLeft: theme.spacing(1),<br>    marginRight: theme.spacing(1),<br>    border: &#39;1px solid red&#39;,<br>  },<br>}));</pre><pre>function App() {<br>  const classes = useStyles();</pre><pre>return (<br>    &lt;TextField<br>      id=&quot;outlined-name&quot;<br>      label=&quot;Name&quot;<br>      className={classes.textField}<br>      margin=&quot;normal&quot;<br>      variant=&quot;outlined&quot;<br>    /&gt;<br>  );<br>}</pre><p>Now, I’ve attached class textField with borderColor being red to TextField and it makes a red border around the TextField but is not what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*BiiZ5sKWsu_0HWKGe_bdbQ.png" /></figure><p>Why is that? Inspection on the control tells us that the class textField is actually applied to the root element of TextField which consists of sub components/elements.</p><p><strong><em>Key point: className is ONLY applied to the root element of MU components.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-Rnius_70kn4zdWKDkT_A.png" /></figure><h3>Mission 1 — Make border red when it’s being hovered over</h3><p>As TextField docs indicate that OutlinedInput will be rendered when variant valued outlined and prop InputProps on TextField can be used to pass any props through to OutlinedInput. It rings the bell!!</p><p>Looking at OutlinedInput docs, it has a quite number of class names that allow you to control its styling. Question here is which class should we look at?</p><p>To work this out, my trick is hover through DOMs as shown in the above screenshot until you see any highlighted DOM exactly covers the text field. In our case, it’s the div with classes —<strong><em>MuiInputBase-root, MuiOutlinedInput-root and Mui-focused Mui-focused MuiInputBase-formControl.</em></strong></p><p>Now, it becomes more clear that we need to overwrite styles in root class.</p><p>However, we will see two borders overlapping each other if we do this:</p><pre>const useStyles = makeStyles(theme =&gt; ({<br>  outlinedRoot: {<br>    &#39;&amp;:hover&#39;: {<br>      border: &#39;1px solid red&#39;,<br>    },<br>}));</pre><pre>...</pre><pre>const InputProps = {<br>    classes: {<br>      root: classes.outlinedRoot,<br>    },<br>  };</pre><pre>return (<br>    &lt;TextField<br>      id=&quot;outlined-name&quot;<br>      label=&quot;Name&quot;<br>      className={classes.textField}<br>      margin=&quot;normal&quot;<br>      variant=&quot;outlined&quot;<br>      InputProps={InputProps}<br>    /&gt;<br>  );<br>}</pre><p>What’s happened was we added border to div shown as makeStyles-outlinedRoot-2but its children fieldset has its own border in grey that’s overlapping div&#39;s one and is highlighted when being hovered over.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXm1ZTyVjdWIJ5kK1k7xmA.png" /></figure><p>Now, it points us to fieldset and we need to find a way to overwrite border-colorvalue:</p><pre>.MuiOutlinedInput-root:hover .MuiOutlinedInput-notchedOutline {<br>   border-color: rgba(0, 0, 0, 0.87);<br>}</pre><p>A translation from css to jss(mui flavor) is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ourcRChpwzrdiEydiqny5Q.png" /></figure><p>Here we use <a href="https://material-ui.com/customization/components/#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet">$ruleName</a> notchedOutline as part of our selector to target the DOM. Let’s reflect it in code and see the effect:</p><pre>const useStyles = makeStyles(theme =&gt; ({<br>  outlinedRoot: {<br>    &#39;&amp;:hover $notchedOutline&#39;: {<br>      borderColor: &#39;red&#39;,<br>    },<br>  },<br>  notchedOutline: {<br>  }<br>}));</pre><pre>...</pre><pre>const InputProps = {<br>    classes: {<br>      root: classes.outlinedRoot,<br>      notchedOutline: classes.notchedOutline<br>    },<br>  };</pre><p>which compiles into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6axkEYlALgxgQjxAhA6qQ.png" /></figure><p>If we now hover over the text field, border colour finally becomes red. Mission one completed!</p><p>Let’s look at mission 2.</p><h3>Mission 2— Make border green when users start typing — focused</h3><p>Likewise, we can follow the same path to get this mission done easily.</p><p>Firstly, figure out what classes fieldset is using when it’s being focused:</p><pre>.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {<br>    border-color: #3f51b5;<br>    border-width: 2px;<br>}</pre><p>The selector has a new member Mui-focused compared to the previous one and based on the translation we’ve worked out before we can quite easily write code below to find the target and overwrite the border-color to make it green.</p><p><strong><em>Tip: If you get annoyed by losing focus on input when you click your mouse elsewhere than input itself, you can simply remove </em></strong><strong><em>blur event from event lists displayed under </em></strong><strong><em>Event Listeners tab.</em></strong></p><pre>const useStyles = makeStyles(theme =&gt; ({<br>  outlinedRoot: {<br>    &#39;&amp;:hover $notchedOutline&#39;: {<br>      borderColor: &#39;red&#39;,<br>    },<br>    &#39;&amp;$focused $notchedOutline&#39;: {<br>      borderColor: &#39;green&#39;,<br>      borderWidth: 1,<br>    },<br>  },<br>  notchedOutline: {},<br>  focused: {},<br>}));</pre><p>And don’t forget to add focusedto classes prop:</p><pre>classes: {<br>  root: classes.outlinedRoot,<br>  notchedOutline: classes.notchedOutline,<br>  focused: classes.focused<br>},</pre><p>Awesome! We now see border turns green when it’s gaining focus.</p><p>I understand it can be a tough time for beginners to get styling with material-ui right and hope this post can help them conquer it.</p><p>😜😜😜</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a44f7c68113" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/my-journey-to-make-styling-with-material-ui-right-6a44f7c68113">My journey to make styling with Material-UI right</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I do integration test for service powered by serverless + dynamoDB using Jest]]></title>
            <link>https://codeburst.io/how-i-do-integration-test-for-service-powered-by-serverless-dynamodb-using-jest-e94f0710d28f?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e94f0710d28f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[integration-testing]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Fri, 10 May 2019 04:01:38 GMT</pubDate>
            <atom:updated>2019-05-13T17:23:38.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*zBG7TG0cSeIHHZ0dUml6iQ.png" /></figure><p>Testing is an important part in today’s apps/services development. Without it, you are scared to modify your code due to the risk of breaking things.</p><p>Basically, testing has 3 forms — Unit Test, Integration Test and E2E Test. They serve different purposes at the different stages of software development.</p><p>In this post, I will be fully focused on Integration testing since doing it properly with <strong>serverless</strong> and <strong>dynamoDB</strong> is tricky. I spent 2 days of trying various approaches and finally came up with the right way.</p><p>This post walks you through the whole journey I’ve gone to get from nothing in hand to a slick solution.</p><h3>The very first attempt</h3><p>To do integration test properly, you need to simulate the entire flow of your service by incorporating the dependent services into your tests. In my case, they are lambda and dynamoDB. Basically, you need to spin them up before your tests can run and stop them when your tests are done.</p><p>The first idea that’s hitting to my mind is by spawning a node child process to start up those services and save the ports somewhere so I can later stop them.</p><p>Since I am using Jest, I will use beforeAll and afterAll hook to trigger the process:</p><pre>const { spawn } = require(&#39;child_process&#39;);</pre><pre>// test_setup.js</pre><pre>const { spawn } = require(&#39;child_process&#39;);</pre><pre>let slsProcess;</pre><pre>const start = () =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    slsProcess = spawn(&#39;yarn&#39;, [&#39;sls-offline&#39;, &#39;--port&#39;, 3000]);</pre><pre>slsProcess.stdout.on(&#39;data&#39;, data =&gt; {<br>      if (data.includes(&#39;Offline listening on&#39;)) {<br>        resolve();<br>      }<br>    });</pre><pre>slsProcess.stderr.on(&#39;data&#39;, err =&gt; {<br>      reject();<br>    });<br>  });<br>};</pre><pre>const stop = () =&gt; {<br>  slsProcess.kill();<br>};</pre><pre>// test.js<br>beforeAll(() =&gt; {<br>  return start();<br>});</pre><pre>afterAll(() =&gt; {<br>  stop();<br>});</pre><p>You also need to do dynamoDB part as well. Now everything has setup and I should be able to run the test and see all green. But unfortunately, it does not work and throws me an error — <strong>Command failed with exit code 1.</strong></p><p>Time to debug to see what’s happened. I inspect the debugging logs which shows little information about what causes the error. I also ask google and none of those results is actually pertinent to my use case.</p><p>Now, I am thinking does that test-setup script work if I run it individually without Jest? Guess what, it’s working like a charm!</p><p>So the problem actually lies in Jest? Maybe.</p><h3>The second attempt</h3><p>Now the question is can I separate the test setup from integration test itself? If the answer is yes, then I can definitely solve this problem. Let’s try!</p><p>With the test-setup in place, I firstly did something like this</p><pre>// package.json</pre><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;node ./test-setup &amp;&amp; yarn test&quot;,<br>  &quot;test&quot;: &quot;jest -c ./jest.config.js --coverage&quot;</pre><pre>}</pre><p>Well, this looks promising but it does not work as a matter of fact. The reason being is your lambda service will not terminate and yarn test will not get a chance to run because there is an active listener that’s created by <strong>http</strong> module for listening for incoming requests.</p><p>To mitigate this problem, we can make the service run at the background instead of foreground.</p><h3><strong>The Solution</strong></h3><p>After two failed attempts, let me review the solution now. I will write shell scripts for the solution.</p><p>In essence, you will need to start the service and redirect the outputs from terminal to a temp file and keep checking the file contents until you see the text “service has started” or something similar that indicates the service is up and running.</p><p>Here is my script for services startup.</p><pre>// start-services.sh</pre><pre>#!/usr/bin/env bash</pre><pre>if [ -f ~/offline.log ]; then<br>  rm -f ~/offline.log<br>fi</pre><pre>if [ -f ~/dynamoDB.log ]; then<br>  rm -f ~/dynamoDB.log<br>fi</pre><pre>source ./stopOffline.sh</pre><pre>TMPFILE=$(mktemp ~/offline.log)<br>TMPDynamoDBFILE=$(mktemp ~/dynamoDB.log)</pre><pre>if [ -f .offline.pid ]; then<br>  echo &quot;Found file .offline.pid. Not starting.&quot;<br>  exit 1<br>fi</pre><pre># &amp;&gt; redirects stderr and stdout<br># &amp; makes the command run in the background and shell does<br># not wait for the command to finish<br>yarn sls-dynamodb-start:test &amp;&gt; $TMPDynamoDBFILE &amp;</pre><pre>while ! grep &quot;Dynamodb Local Started&quot; $TMPDynamoDBFILE<br>do<br>  sleep 2;<br>done</pre><pre># start up serverless<br># $! is the pid of the last program your shell ran in the background<br>yarn sls-offline &amp;&gt; $TMPFILE &amp;<br>PID=$!<br>echo $PID &gt; .offline.pid</pre><pre>while ! grep &quot;Offline listening&quot; $TMPFILE<br>do<br>  sleep 1;<br>done</pre><pre>rm -f $TMPFILE<br>rm -f $TMPDynamoFILE</pre><p>Once required services are ready, next thing is run your tests. Given it’s integration test, it should be as simple as this:</p><pre>const request = require(&#39;supertest&#39;);</pre><pre>describe(&#39;call serverless service&#39;, () =&gt; {<br>  const server = request(&#39;<a href="http://localhost:3000&#39;">http://localhost:3000&#39;</a>);</pre><pre>it(&#39;GET /navigation/123&#39;, done =&gt; {<br>    server<br>      .get(&#39;/navigation/123&#39;)<br>      .expect(200)<br>      .expect(&#39;content-Type&#39;, /json/)<br>      .end((error: any, result: any) =&gt; {<br>        if (error) return done(error);<br>        // check the response<br>        return done();<br>      });<br>  });<br>});</pre><p>Lastly, don’t forget to terminate your services:</p><pre>#!/usr/bin/env bash</pre><pre># Things between backticks is evaluated by the shell<br>if [ -f ./.offline.pid ]; then<br>  kill `cat .offline.pid`<br>  rm -f .offline.pid<br>fi</pre><pre>RES=`lsof -t -i:8000`</pre><pre>if [ &quot;$RES&quot; != &#39;&#39; ]; then<br>  # kill DynamoDB local<br>  kill `lsof -t -i:8000`<br>fi</pre><p>By far, we have done every single bit to run our integration test. Let’s add commands to npm scripts section to automate the whole test process.</p><pre>{<br>    &quot;scripts&quot;: {<br>        &quot;test&quot;: &quot;yarn service:start &amp;&amp; jest -c ../../jest.config.js --coverage &amp;&amp; yarn service:stop&quot;,<br>        &quot;service:start&quot;: &quot;node -e &#39;require(\&quot;shelljs\&quot;).exec(\&quot;./startServices.sh\&quot;)&#39;&quot;,<br>        &quot;service:stop&quot;: &quot;node -e &#39;require(\&quot;shelljs\&quot;).exec(\&quot;./stopServices.sh\&quot;)&#39;&quot;,<br>    },<br>}</pre><p>Note: I initially tried to execute shell script directly without using <a href="https://github.com/shelljs/shelljs">shelljs</a> module. But it didn’t work and got me a weird error that I have no idea how I can get around it.</p><p>This’s it, hope you find this post useful and clap it hard. 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e94f0710d28f" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/how-i-do-integration-test-for-service-powered-by-serverless-dynamodb-using-jest-e94f0710d28f">How I do integration test for service powered by serverless + dynamoDB using Jest</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use custom directives to protect your graphql apis]]></title>
            <link>https://codeburst.io/use-custom-directives-to-protect-your-graphql-apis-a78cbbe17355?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a78cbbe17355</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Sun, 18 Feb 2018 00:19:54 GMT</pubDate>
            <atom:updated>2018-02-20T01:50:38.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4fIqzeF51qevwvrHo-gIDw.jpeg" /></figure><p>Authentication is required for apps that not only have public api endpoints but also authenticated ones that are accessible to users with certain level of access. In REST world, we will normally attach authentication bit (token verification) to the middleware before requests hitting the actual route.</p><p>Take express for instance, we can use passport to verify the token that is set on request header. If JWT token contains expected scope, we will let the request through to route handler to process or otherwise rejects it with proper errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c8f7180ceb8f42a9ff2bce2315fcbba/href">https://medium.com/media/8c8f7180ceb8f42a9ff2bce2315fcbba/href</a></iframe><p>But, can we follow this pattern on our Graphql server?</p><p>Well, the answer is — it really depends.</p><p>In the following section, I will show you how you can implement authentication on your graphql server using middleware pattern.</p><p>Please note, I will only provide a high level overview and for the complete working example, please refer to <a href="https://github.com/jessedvrs/graphql-passport-example">https://github.com/jessedvrs/graphql-passport-example</a>.</p><h3>Auth your apis via express middleware pattern</h3><p>I will use <a href="http://www.passportjs.org/">passport </a>to give us a helping hand in authentications. Firstly, let’s code the authentication strategy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8614cd0f78c41c124758645a83153f/href">https://medium.com/media/fb8614cd0f78c41c124758645a83153f/href</a></iframe><p>Next, add auth middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d26bd469fb66b0d0f794f47641fab2/href">https://medium.com/media/d8d26bd469fb66b0d0f794f47641fab2/href</a></iframe><p>Finally, register middlewares:</p><pre>const app = express();<br>app.use(authMiddleware);<br>app.use(&#39;/api/graphql&#39;, graphqlMiddleware);</pre><p>Voila! Now you are able to retrieve user object that is available in your resolver:</p><pre>export default {<br>  cakes: {<br>    type: new GraphQLList(CakeType),<br>    resolve: (_, args, context) =&gt; {<br>      if (!context.user) {<br>        throw new Error(&#39;Only users can eat cakes.&#39;);<br>      }<br>      return [{flavour: &#39;red-velvet&#39;}, {flavour: &#39;mocca&#39;}];<br>    },<br>  },<br>};</pre><p>It gets the job done for sure but it lacks flexibility and has downsides:</p><ul><li>All apis must be authenticated against callers even though you have public apis since auth is applied to middleware</li><li>Scope check cannot be done once — you need to do it in route handlers where certain level of access is required</li><li>Could be tricky to implement granular scope check on specific fields in type</li></ul><p>With custom directives, you can easily resolve those issues mentioned above.<br>Keep reading on!</p><p><strong><em>Note: I assume you already have a basic understanding of how directives work in graphql. If that sounds unfamiliar to you, make sure you take time to read the post below to wrap your head around this concept.</em></strong></p><p><a href="https://medium.com/front-end-developers/graphql-directives-3dec6106c384">graphql directives</a></p><h3>The custom directives way</h3><p>In this section, I will build a simple products supply server to illustrate my way of authentication implementation via custom directives.</p><p>Essentially, I will break the implementations into two parts:</p><ul><li>Schema</li><li>Directive and Query/Mutation resolvers</li></ul><p>Let’s start!</p><h4>Add schema</h4><p>First thing first, let’s define our two custom directives:</p><pre>directive <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a> on QUERY | FIELD<br>directive <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [String]) on QUERY | FIELD</pre><p>Two things need to be pointed out:</p><ul><li>QUERY | FIELD indicates that this directive can be applied to both field and query level.</li><li>In hasScope directive, it takes scope as a parameter which is an array of scopes in string representation.</li></ul><p>Now, we have required directives defined. Great!</p><p>Next thing is about how and where we can use them. In this demo app, we have three query operations and one mutation operation.</p><ul><li>allProductBySupplier</li><li>product</li><li>addProduct</li><li>suppliers</li></ul><p>We will make allProductBySupplier, product and addProduct authenticated while leave suppliers public.</p><pre>type Query {<br> allProductsBySupplier: [Product] <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a><br> product: Product <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a><br> suppliers: [Supplier]<br>}<br>type Mutation {<br> addProduct(input: ProductInput!): Product <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [“add:product”])<br>}</pre><p>As you can see, @isAuthenticated is applied to the non-public queries on query level.</p><p>For mutation, we require users who want to add product must have add:product scope. Similarly, we will also restrict who can read <strong>rating </strong>from product to only users who have read:rating scope.</p><pre>…<br> type Product {<br>  id: ID!<br>  supplierId: ID!<br>  sku: String<br>  qty: Int<br>  price: Int<br>  parrot: String<br>  rating: Int <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [“read:rating”])<br> }<br>…</pre><p>Here is the complete schema:</p><pre>directive <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a> on QUERY | FIELD<br>directive <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [String]) on QUERY | FIELD</pre><pre>type Product {<br>  id: ID!<br>  supplierId: ID!<br>  sku: String<br>  qty: Int<br>  price: Int<br>  parrot: String<br>  rating: Int <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [&quot;read:rating&quot;])<br>}</pre><pre>type Supplier {<br>  id: ID!<br>  name: String!<br>}</pre><pre>input ProductInput {<br>  supplierId: ID!<br>  sku: String!<br>  qty: Int!<br>  price: Int!<br>  parrot: String!<br>  rating: Int!<br>}</pre><pre>type Query {<br>  allProductsBySupplier: [Product] <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a><br>  product: Product <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a><br>  suppliers: [Supplier]<br>}</pre><pre>type Mutation {<br>  addProduct(input: ProductInput!): Product <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [&quot;add:product&quot;])<br>}</pre><p>Schema is ready now! let’s walk into next square — build query resolvers!</p><h4>Add Resolvers</h4><p>We will begin with custom directive resolvers — isAuthenticated and hasScope.</p><p>The idea here is we will want to read the Jwt token from authorization header set by the client and decode it to verify.</p><p>If it is not compromised, we then set the decoded value (user in our case) to context which will be available in all resolvers — i.e query resolvers.</p><p>Once we have the user set on context, next thing is to trigger next which is our query resolver to resolve each field.</p><p>In the case of invalid token, we should simply reject the requests by throwing errors.</p><p>isAuthenticated is implemented as follow:</p><pre>isAuthenticated: (next, source, args, context) =&gt; {<br>  const token = context.headers.authorization;<br>  if (!token) {<br>    throw new AuthorizationError({<br>      message: &quot;You must supply a JWT for authorization!&quot;<br>    });<br>  }<br>  try {<br>    const decoded = jwt.verify(<br>      token.replace(&quot;Bearer &quot;, &quot;&quot;),<br>      process.env.JWT_SECRET<br>    );<br>    context.user = decoded;<br>    return next();<br>  } catch (err) {<br>    throw new AuthorizationError({<br>      message: &quot;You are not authorized.&quot;<br>    });<br>  }<br>};</pre><p>hasScope behaves similarly to isAuthenticatedexcept that it does not need to set the user on context:</p><pre>hasScope: (next, source, args, context) =&gt; {<br>    const token = context.headers.authorization;<br>    const expectedScopes = args.scope;<br>    if (!token) {<br>      throw new AuthorizationError({<br>        message: &#39;You must supply a JWT for authorization!&#39;<br>      });<br>    }<br>    try {<br>      const decoded = jwt.verify(<br>        token.replace(&#39;Bearer &#39;, &#39;&#39;),<br>        process.env.JWT_SECRET<br>      );<br>      const scopes = decoded.scope.split(&#39; &#39;);<br>      if (expectedScopes.some(scope =&gt; scopes.indexOf(scope) !== -1)) {<br>        return next();<br>      }<br>    } catch (err) {<br>      return Promise.reject(<br>        new AuthorizationError({<br>          message: `You are not authorized. Expected scopes: ${expectedScopes.join(<br>            &#39;, &#39;<br>          )}`<br>        })<br>      );<br>    }<br>  }</pre><p>Query and mutation resolvers are not fancy and full code is given below:</p><pre>let PRODUCTS = require(&#39;./products&#39;);<br>let SUPPLIERS = require(&#39;./suppliers&#39;);</pre><pre>const allProductsBySupplier = (obj, args, ctx) =&gt; PRODUCTS.filter(p =&gt; p.supplierId === Number(ctx.user.sub));</pre><pre>const addProduct = (obj, args, ctx) =&gt; {<br>  const id = PRODUCTS.length + 1;<br>  PRODUCTS.push({<br>    ...args.input,<br>    id<br>  });<br>  return PRODUCTS.slice(-1)[0];<br>};</pre><pre>const product = (obj, args, ctx) =&gt; PRODUCTS.find(p =&gt; p.id === args.productId);</pre><pre>const suppliers = (obj, args, ctx) =&gt; SUPPLIERS;</pre><pre>module.exports = {allProductsBySupplier, product, suppliers, addProduct};</pre><h4>Glue all together</h4><p>Up to this point, we have everything in place to protect our apis. The last bit is wire all these up into graphql server.</p><p>In the newer version of graphql-tools, makeExecutableSchema accepts one more parameter called directiveResolvers that allows us to attach custom directive resolvers to schema.</p><pre>…<br>const resolvers = {<br>  Query: {<br>    allProductsBySupplier,<br>    product,<br>    suppliers<br>  },<br>  Mutation: {<br>   addProduct<br>  }<br>};</pre><pre>const schema = makeExecutableSchema({<br>  typeDefs,<br>  resolvers,<br>  directiveResolvers<br>});<br>…</pre><h4>Demo</h4><p>Demo time! We will use node-fetch to make our requests to the app server.</p><p>Copy token from section <strong>Supplier 1 JWT with ‘read:rating’ scope </strong>and paste it into Authorization header in client.js.</p><p>Start the server by running npm run dev and once server is up and running, go to terminal and run node client.js.</p><p>You should be able to see a list of products with rating filled up if token is valid.</p><p>Take your time and play with it to find more fun!</p><h4>Last note</h4><p>Before I let you go, there is one important thing I would like to point out — flow of resolvers execution</p><p>Recall how we use isAuthenticated:</p><pre>type Query {<br>  allProductsBySupplier: [Product] <a href="http://twitter.com/isAuthenticated">@isAuthenticated</a><br>}</pre><p>It is applied to query level and will run first before allProductsBySupplierin the above example.</p><p>This is why we need to call next upon successful token verification to execute next resolver.</p><p>hasScope on the other hand is attached to the field:</p><pre>type Product {<br>  …<br>  rating: Int <a href="http://twitter.com/hasScope">@hasScope</a>(scope: [“read:rating”])<br>  …<br>}</pre><p>Therefore, it will be run later than query resolvers in which case rating will be returned from the query resolver to hasScopewhere it will be either set to null or retained depending on the required scope of that user.</p><h3>Conclusion</h3><p>As you can see, have your apis protected through custom directive is more flexible than express middlware approach. Apart from this, custom directives also allow you to do more cool stuff such as capitalize the field value before it reaches query resolvers.</p><p>If you are interested in seeing potential power of custom directive, check <a href="https://github.com/smooth-code/graphql-directive">Custom directives</a></p><h3>Credits</h3><p>Special thanks to Ryan Chenkie who gave the talk on how to do auth in graphql.</p><ul><li><a href="https://www.youtube.com/watch?v=4_Bcw7BULC8&amp;t=569s">Chenkie’s talk on auth in graphql</a></li><li><a href="http://jwtbuilder.jamiekurtz.com/">JWT Builder</a></li></ul><p><a href="https://github.com/DavidHe1127/aws-cognito-example/tree/master/server">Repo on Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a78cbbe17355" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/use-custom-directives-to-protect-your-graphql-apis-a78cbbe17355">Use custom directives to protect your graphql apis</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promise error handling in-depth]]></title>
            <link>https://codeburst.io/promise-error-handling-in-depth-90b0965149c0?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b0965149c0</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 12:08:54 GMT</pubDate>
            <atom:updated>2017-09-24T14:50:27.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*3L5-diirfkPvGH4nE-S7TQ.jpeg" /><figcaption>Dig deep!</figcaption></figure><p>In my earlier blog I have discussed basics of Promise and brief on how we should handle errors correctly. While it covers basics, it does not talk about common questions Promise users would come across during development.</p><p>So, I spent one hour having a deep dig around error handling in Promise and had figured out the answers.</p><p>This blog is written in Q and A form and targeting those who are looking for the answers.</p><p><strong><em>Q1: What will trigger </em></strong><strong><em>catch?</em></strong></p><p>A1: catch will be called when a promise is rejected. Typically, we reject a promise by calling reject(reason).</p><p>Besides, there are another three scenarios causing a promise to be rejected as well.</p><p>The first one is programmer errors.</p><blockquote>They are bugs in the program. These are things that can always be avoided by changing the code. They can never be handled properly (since by definition the code in question is broken).</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80cca8be027cacc4c6c71a4d5b01bcde/href">https://medium.com/media/80cca8be027cacc4c6c71a4d5b01bcde/href</a></iframe><p>Secondly, explicitly throw errors will achieve the same result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7852540ad8b735580ba325716665886/href">https://medium.com/media/d7852540ad8b735580ba325716665886/href</a></iframe><p>Finally, it is the rejected nested promise. What I mean by this is the rejected state of nested promise bubbles up which makes the root promise rejected as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5362efd88d504a99c0487b07b0b63426/href">https://medium.com/media/5362efd88d504a99c0487b07b0b63426/href</a></iframe><p>We can see that the whole promise asyncTask is rejected due to rejected asyncTask2.</p><p>To summarise, 3 ways below can lead to a rejected promise.</p><ul><li>Programmer errors (bugs) in promise constructor</li><li>Throw errors</li><li>Nested rejected promise</li></ul><p><strong><em>Q2: What area does a catch monitor?</em></strong></p><p>A2: Dead simple! Just keep this in mind — catch will look over every place (then and async operations) up the promise chain but right before another catch that is located higher.</p><pre>asyncTask()<br>  .then()<br>  .then()<br>  .then()<br>  .catch() // covers promise constructor in asyncTask and 3 then</pre><pre>asyncTask()<br>  .catch() // only covers promise constructor in asyncTask<br>  .then()<br>  .then()<br>  .catch() // 2 then</pre><p>One thing to note here is catch also returns a new promise object that is chainable like then.</p><p><strong><em>Q3: Can I throw an error in catch?</em></strong></p><p>A3: Yes, you can. Error that is thrown in the catch will be caught in the next catch.</p><pre>asyncTask()<br>  .then()<br>  .then()<br>  .catch(err =&gt; {throw new Error(&#39;operation failed&#39;)})<br>  .catch(err =&gt; console.log(err)) // operation failed</pre><p>Error handling in promise can be tricky. I hope those who are still unclear about error handling can benefit from this blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b0965149c0" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/promise-error-handling-in-depth-90b0965149c0">Promise error handling in-depth</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand async/await better]]></title>
            <link>https://codeburst.io/understand-async-await-better-7a03aeba60fe?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a03aeba60fe</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 00:33:05 GMT</pubDate>
            <atom:updated>2017-11-05T00:48:19.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzjdnbtBGdLeSgblBreXzg.jpeg" /></figure><p>Async/Awaitfinally comes to Node V8 after quite a period of time. There are plenty of articles on Medium blogging about why they are better than promise-based asyc solutions and how you should use them. If you unfamiliar with async/await, take your time to read these articles to wrap your head around it and then come back to this article.</p><p>In this article, I will cover some aspects you need to be aware of when working with async/await.</p><p>Code below will be used throughout this blog.</p><pre>const getProduct = product =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      if (product) {<br>        resolve({<br>          product<br>        });<br>      } else {<br>        reject(new Error(&#39;product not specified&#39;));<br>      }<br>    }, 1000);<br>  });<br>};</pre><pre>function getProductNames() {<br>  return Promise.resolve([&#39;apple&#39;, &#39;pear&#39;, &#39;mango&#39;]);<br>}</pre><h3>Await returns resolved value of a Promise</h3><p>Basically, awaitis followed by a promise instance and returns the <strong>resolved</strong> value upon execution.</p><p>This means you cannot chain returned value using thenlike you would with Promise.</p><pre>async function printProduct() {<br>  const product = await getProduct(&#39;pineapple&#39;);</pre><pre>product.then() // error then is not a function!<br>}</pre><p>Let’s tweak getProducta bit to resolve with another promise.</p><pre>...<br>if (product) {<br>  resolve(new Promise((resolve, reject) =&gt; {<br>    setTimeout(x =&gt; {<br>      resolve({<br>        product<br>      });<br>    }, 5000);<br>  }));<br>}<br>...</pre><p>Now, let’s try it again. Oops! In 5 seconds time, you still see the same error again since what await does is like — <strong><em>I promise that I will wait for no matter how long I need to before it gets resolved</em></strong>.</p><h3>Async returns a promise</h3><p>This allows you to chain promise using then:</p><pre>async function printProduct() {<br>  return await getProduct(&#39;pineapple&#39;);<br>}</pre><pre>var prod = printProduct();</pre><pre>prod.then(x =&gt; {<br>  console.log(x);<br>});</pre><p>This also allows for another way of handling errors apart from try/catchthat we all know:</p><pre>async function printProduct() {<br>  console.log(afffa);<br>  return await getProduct(&#39;pineapple&#39;);<br>}</pre><pre>var prod = printProduct();</pre><pre>prod.catch(err =&gt; {<br>  console.log(err); // error caught!<br>});</pre><p><em>Thanks for </em><a href="https://medium.com/u/daa154cd965b"><em>YingshanDeng</em></a><em>’s point that you do need the </em><em>await in the above code since the return value of </em><em>async will be implicitly wrapped in </em><em>Promise.resolve.</em></p><h3>Use for…of when you need to control the flow</h3><p>Let’s call getProducton each of products returned by calling getProductNamesand see what will happen.</p><pre>async function printProduct() {<br>  const products = await getProductNames();<br>  products.forEach(async x =&gt; {<br>    const prod = await getProduct(x);<br>    console.log(prod);<br>  });<br>}</pre><p>Console prints out the output below in one go after 1 second.</p><pre>{ product: &#39;apple&#39; }<br>{ product: &#39;pear&#39; }<br>{ product: &#39;mango&#39; }</pre><p>This is working fine but not what we actually expect to see. Instead, we want them to happen in order one after another. The problem with using normal forEachis that it does not wait until the previous promise is resolved before it starts to run the next one.</p><p>Given the fact that Array itself has iteratorinterface and can be looped using for...of. So the solution is to use for...ofwhich is designed to work with collections like Array, Map, Set, Generator. What it does is it will call nextto move onto next element when the previous one has been resolved.</p><pre>async function printProduct() {<br>  const products = await getProductNames();<br>  for (const r of products) {<br>    const readContents = await getProduct(r); // await is a **MUST**<br>    console.log(readContents);<br>  }<br>}</pre><p>Now we are talking and seeing each fruit is printed out in every one second.</p><p>Please be mindful that you must annotate getProduct with keyword await even though you don’t need its async resolved value otherwise process will not wait until getProduct gets resolved before it loops the next iteration.</p><p>Other than running them in a series, we can also run them in parallel:</p><pre>async function printProduct () {<br>  const products = await getProductNames();</pre><pre>const promises = products.map(p =&gt; getProduct(p));<br>  let results = [];</pre><pre>for (let promise of promises) {<br>    results.push(await promise);<br>  }<br>}</pre><p>Alternatively, we can use Promise.allto achieve the same behaviour.</p><pre>async function printProduct () {<br>  const products = await getProductNames();<br>  const promises = products.map(p =&gt; getProduct(p));<br>  let results = [];<br>  results = await Promise.all(promises);<br>}</pre><h3>Conclusion</h3><p>Async/Await really makes our async operations much easier. Hopefully, this article makes you have a better understanding of how Async/Awaitworks so that you can start using it if you haven’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a03aeba60fe" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/understand-async-await-better-7a03aeba60fe">Understand async/await better</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why my react component re-renders?]]></title>
            <link>https://codeburst.io/why-my-react-component-re-renders-a0d23614fab?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d23614fab</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Mon, 17 Jul 2017 13:42:37 GMT</pubDate>
            <atom:updated>2018-04-16T00:11:05.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhptQ8j6GcbZrv_NW0HG_w.png" /></figure><p>Today, I run into an issue that the seemingly working code produces. After half hour of poking around, I still could not figure out the reason why my stateless and functional component keeps re-rendering. Finally, I turn to discord and @BTM helps me out (Thanks for his assistance).</p><p>This story will cover the issue and the solution to it.</p><p>Basically, I have 3 components A, B and C. And A renders B which renders C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*-36JytgNmXTeUbZ7-hccQQ.png" /><figcaption>View Hierachy</figcaption></figure><p>Component A:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b940dd4d861f1076a4df73c96ec035a/href">https://medium.com/media/3b940dd4d861f1076a4df73c96ec035a/href</a></iframe><p>The code above looks normal and reasonable at the first sight. But it causes a problem that &lt;AmountOwing /&gt; input loses the focus when I start typing. In the first first place, I thought it might to do with component A. But it is actually a red-herring after another close look into the code.</p><p>So, what is going on here?</p><p>B takes onChange and existingAmountOwing and correctly sets them and triggers onChange to update the existingAmountOwing…</p><p>Now, let me tell you why — a new instance of &lt;AmountOwing /&gt; is re-painted every time there is a change!!! As a result, a new input is generated which replaces the focused one.</p><p>Why is that?</p><p>The problem lies in code below</p><pre>const AmountOwing = () =&gt;<br>    &lt;input<br>      prefix=&quot;$&quot;<br>      size=&quot;large&quot;<br>      name=&quot;existingAmountOwing&quot;<br>      onChange={onChange}<br>      type=&quot;number&quot;<br>      placeholder=&quot;0&quot;<br>      value={existingAmountOwing}<br>      id=&quot;amount&quot;<br>    /&gt;;</pre><p>what it does is : it creates a new instance of functional component which breaks my stuff!</p><blockquote>Defining functional components inside another functional components OR inside render of class-based components is considered to be anti-pattern since React will not be able to diff those effectively because they have a new type on every render.</blockquote><p>Above is quoted from <strong><em>Dan Abramov.</em></strong></p><p>Since AmountOwing is a functional component typed a reference that points to the function itself, every render will create a new function with a different reference. As a result, type is changed apparently.</p><p>Things to remember — React uses === to compare two types.</p><p>The fix is easy:</p><pre>const AmountOwing = (<br>    &lt;input<br>      prefix=&quot;$&quot;<br>      size=&quot;large&quot;<br>      name=&quot;existingAmountOwing&quot;<br>      onChange={onChange}<br>      type=&quot;number&quot;<br>      placeholder=&quot;0&quot;<br>      value={existingAmountOwing}<br>      id=&quot;amount&quot;<br>    /&gt;<br>  );</pre><pre>return AmountOwing;</pre><p>You might ask why not just return &lt;input .../&gt; ???</p><p>Ok, actually I have a bunch of text inputs that need to be rendered conditionally and would like to have a fairly intuitive and clean render that shows what it renders given the specific conditions.</p><p>As thus, instead of structuring code like</p><pre>if (conditionA) {<br>    return (<br>      &lt;div&gt;<br>        &lt;Row&gt;<br>          &lt;span&gt;Interest Rate&lt;/span&gt;<br>          &lt;input<br>            name=&quot;interestRate&quot;<br>            onChange={onChange}<br>            type=&quot;number&quot;<br>            placeholder=&quot;0&quot;<br>            value={interestRate}<br>          /&gt;<br>        &lt;/Row&gt;<br>        &lt;Row&gt;<br>          &lt;span&gt;Amount Owing&lt;/span&gt;<br>          &lt;input<br>            name=&quot;existingAmountOwing&quot;<br>            onChange={onChange}<br>            type=&quot;number&quot;<br>            placeholder=&quot;0&quot;<br>            value={existingAmountOwing}<br>          /&gt;<br>        &lt;/Row&gt;<br>      &lt;/div&gt;<br>    );<br>  } else if (conditionB) {<br>    return (<br>      &lt;div&gt;<br>        &lt;Row&gt;<br>          &lt;span&gt;Interest Rate&lt;/span&gt;<br>          &lt;input<br>            name=&quot;interestRate&quot;<br>            onChange={onChange}<br>            type=&quot;number&quot;<br>            placeholder=&quot;0&quot;<br>            value={interestRate}<br>          /&gt;<br>        &lt;/Row&gt;<br>        &lt;Row&gt;<br>          &lt;span&gt;Extra Contributions&lt;/span&gt;<br>          &lt;input<br>            prefix=&quot;$&quot;<br>            name=&quot;extraContributions&quot;<br>            onChange={onChange}<br>            type=&quot;number&quot;<br>            placeholder=&quot;0&quot;<br>            value={extraContributions}<br>          /&gt;<br>        &lt;/Row&gt;<br>      &lt;/div&gt;<br>    );<br>  }</pre><p>which is a bit hard to tell what it renders. I prefer to doing in a terse way below:</p><pre>const interestRate = (<br>    &lt;Row&gt;<br>      &lt;span&gt;Interest Rate&lt;/span&gt;<br>      &lt;input<br>        name=&quot;interestRate&quot;<br>        onChange={onChange}<br>        type=&quot;number&quot;<br>        placeholder=&quot;0&quot;<br>        value={interestRate}<br>      /&gt;<br>    &lt;/Row&gt;<br>  );</pre><pre>let AmountOwing, extraContributions;</pre><pre>if (conditionA) {<br>    AmountOwing = (<br>      &lt;Row&gt;<br>        &lt;span&gt;Amount Owing&lt;/span&gt;<br>        &lt;input<br>          name=&quot;existingAmountOwing&quot;<br>          onChange={onChange}<br>          type=&quot;number&quot;<br>          placeholder=&quot;0&quot;<br>          value={existingAmountOwing}<br>        /&gt;<br>      &lt;/Row&gt;<br>    );<br>  } else if (conditionB) {<br>    extraContributions = (<br>      &lt;Row&gt;<br>        &lt;span&gt;Extra Contributions&lt;/span&gt;<br>        &lt;input<br>          prefix=&quot;$&quot;<br>          name=&quot;extraContributions&quot;<br>          onChange={onChange}<br>          type=&quot;number&quot;<br>          placeholder=&quot;0&quot;<br>          value={extraContributions}<br>        /&gt;<br>      &lt;/Row&gt;<br>    );<br>  }</pre><pre>return (<br>    &lt;div&gt;<br>      {conditionA &amp;&amp; [AmountOwing, interestRate]}<br>      {conditionB &amp;&amp; [extraContributions, interestRate]}<br>    &lt;/div&gt;<br>  );</pre><p>Now, you can quickly tell what needs to be rendered under which condition.</p><p>I see a well-known issue that causes input to lose focus is forget to specify key on component being created in a for loop.</p><pre>for (var i = 0; i &lt; recipients.length; i++) {<br>  children.push(<br>  &lt;input<br>    type=&quot;email&quot;<br>    value={recipients[i]}<br>    onChange={this.props.recipientEmailChangedHandler.bind(null, i)}<br>  /&gt;)<br>}</pre><p>Now, I give you another potential cause of such problem. Make sure you examine how your component gets created and rendered next time you are the victim like me.</p><p>Before I put a full stop to this story, I would like to restate this rule again:</p><ol><li>make it work</li><li>make it look good</li></ol><p>Order does matter like middleware!! Not the other way around!</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d23614fab" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/why-my-react-component-re-renders-a0d23614fab">Why my react component re-renders?</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything you should know about Promise]]></title>
            <link>https://codeburst.io/everything-you-should-know-about-promise-a05a20bf4c53?source=rss-b498ae8d18e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a05a20bf4c53</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[David He]]></dc:creator>
            <pubDate>Sun, 09 Jul 2017 13:07:10 GMT</pubDate>
            <atom:updated>2017-07-11T11:48:47.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sKRjbOKszhQGpKrILXcvDg.jpeg" /></figure><p>Promise has been out in the wild for a few years and heaps of API libraries wrap them up for users to make async operations with ease. We all know we can make the async call as below</p><pre>someAsyncCall.then(res =&gt; res.data).then();</pre><p>But I am sure some beginners do not know how Promise works and what they need to be mindful when using or building their own promise.</p><p>If you are among those, take your time to read through. I will cover everything about Promise inside out.</p><p>I will refer successful and failed callbacks set on then to onResolved and onRejected throughout the writing.</p><p>Code below will be used for illustration.</p><pre>const delJSON = (url) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(function() {<br>      if (url) {<br>        resolve({<br>          message: &#39;deleted&#39;,<br>          id: 2<br>        });<br>      } else {<br>        reject({<br>          error: &#39;delJSON failed&#39;<br>        });<br>      }<br>    }, 500);<br>  });<br>};</pre><pre>const getJSON = (url) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(function() {<br>      if (url) {<br>        resolve({<br>          data: [1, 2],<br>          id: 1<br>        });<br>      } else {<br>        reject({<br>          error: &#39;getJSON failed&#39;<br>        });<br>      }<br>    }, 2000);<br>  });<br>};</pre><h3>Basics</h3><h4>Three states of Promise</h4><p>A Promise can only be one of these three states as follow:</p><ol><li>Pending: Initial state</li><li>Resolved: Operation succeeded</li><li>Rejected: Operation failed</li></ol><p>The only way for <strong>Pending </strong>to turn into <strong>Resolved </strong>or <strong>Rejected </strong>is by calling resolve(value) or reject(error).</p><p>Once the state is changed, you cannot roll back to Pending. It will stay permanently.</p><h4>Promise initialisation</h4><p>Call constructor Promise to return an instance.</p><pre>promise.then(function(data) {<br>  // success<br>}, function(error) {<br>  // failure<br>});</pre><p>Promise constructor takes a function as its only one argument that has resolve and reject as the function parameters. Calling resolve with value will trigger onResolved that is set by calling then on a Promise instance. Similarly, calling reject with error will trigger onRejected.</p><p>onRejected callback is optional but it is highly suggested to set it in order to handle the errors.</p><p>One thing to keep in mind is that Promise acts as a container which contains the future result of operations. They are executed once they are created.</p><pre>let promise = new Promise(function(resolve, reject) {<br>  console.log(&#39;start&#39;);<br>  resolve();<br>});</pre><pre>promise.then(function() {<br>  console.log(&#39;done&#39;);<br>});</pre><pre>console.log(&#39;ok&#39;);</pre><pre>// start<br>// ok<br>// done</pre><h4>Then</h4><p>All promise instances have then method which is used to add two callbacks : onResolved and onRejected.</p><pre>const onResolved = (data) =&gt; {return data.id};<br>const onRejected = (error) =&gt; {};</pre><pre>promise.then(onResolved, onRejected).then(id =&gt; console.log(id));</pre><p>You can chain then by returning the value which is then be wrapped into another new promise instance.</p><h4>Catch</h4><p>catch is a sugar syntax for .then(null, onRejected) which is triggered when there is an error.</p><pre>getJSON().then(data =&gt; {<br>}).catch(err =&gt; {<br>  // {error: &#39;getJSON failed&#39;}<br>});</pre><h4>All</h4><p>You can use Promise.all to run multiple operations.</p><pre>const p = Promise.all([p1, p2, p3]);</pre><p>Typically, Promise.all takes an array of promise instances which determines the final state for the returned promise from calling Promise.all.</p><p>Let’s look at how we resolve p first.</p><p>Basically, for p to be resolved, p1,p2,p3 all need to be resolved.</p><pre>const p = Promise.all([getJSON(&#39;baidu.com&#39;), delJSON(&#39;google.com&#39;)]);</pre><pre>p.then(data =&gt; data).catch(err =&gt; console.log(err));</pre><pre>// [{data: [1,2], id: 1}, {message: &#39;deleted&#39;, id: 2}]</pre><p>As you can see, the resolved values will be passed to onResolved in the same order as we create all promise instances.</p><p>Now, let’s look at the rejected case. If anyone of instances gets rejected, p will be rejected and the reason for the firstly-rejected promise will be passed to onRejected.</p><pre>const p = Promise.all([getJSON(&#39;baidu.com&#39;), delJSON()]);</pre><pre>p.then(data =&gt; console.log(data)).catch(err =&gt; console.log(err));</pre><pre>// {error: &#39;delJSON failed&#39;}</pre><h4>Race</h4><p>It is quite self-explanatory — the first resolved or rejected promise will determine the state of the promise instance created by race.</p><pre>const p = Promise.race([getJSON(&#39;baidu.com&#39;), delJSON(&#39;google.com&#39;)]);</pre><pre>p.then(data =&gt; console.log(data)).catch(err =&gt; console.log(err));</pre><pre>// { message: &#39;deleted&#39;, id: 2 }</pre><h3>Advanced</h3><h4>Resolve with another promise instance</h4><p>I would like to call this scenario a nested promise. Nested promise will determine the outside promise state.</p><pre>getJSON(&#39;baidu.com&#39;).then(data =&gt; {<br>  console.log(data); // not called<br>}).catch(err =&gt; {<br>  console.log(&#39;the error &#39;, err);<br>  // {error: &#39;operation failed&#39;}<br>});</pre><pre>const delJSON = (url) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(function() {<br>      if (url) {<br>        resolve({<br>          message: &#39;deleted&#39;,<br>          id: 2<br>        });<br>      } else {<br>        reject({<br>          error: &#39;delJSON failed&#39;<br>        });<br>      }<br>    }, 500);<br>  });</pre><pre>};</pre><p>In the above example, you might think then will be called, but that is not the case, instead catch will be triggered since nested promise delJSON takes the control. In other words, inner promise state overrides the outside one.</p><h4>Error handling</h4><p>You might wonder which is the preferred way to handle errors between setting onRejected or using catch. The answer is latter — catch. The problem with onRejected is if an error happens in onResolved, onRejected will simply turn bind eyes to it whereas catch will catch it!</p><pre>getJSON(&#39;baidu.com&#39;).then(data =&gt; {<br>  [].move();<br>}, (err) =&gt; {<br>  console.log(&#39;operation failed&#39;, err);  // turn blind eyes to error<br>});</pre><pre>delJSON(&#39;google.com&#39;).then(data =&gt; {<br>  [].move();<br>}).catch(err =&gt; {<br>  console.log(&#39;operation failed&#39;, err); // caught! since I see it<br>});</pre><p>You can also use catch for catching errors of separate operations.</p><pre>getJSON(&#39;baidu.com&#39;).then(data =&gt; {<br>  data.move();<br>}).catch(err =&gt; {<br>  console.log(&#39;1st error &#39;, err);<br>}).then(data =&gt; {<br>  data.move();<br>}).catch(err =&gt; {<br>  console.log(&#39;2nd error &#39;, err);<br>});</pre><pre>// prints both errors</pre><p>Catch allows you to catch errors in these places effectively.</p><ul><li>Promise constructor function argument</li><li>onResolved</li><li>functions returning a new promise instance in onResolved</li></ul><p>However, error below will not be caught since promise is already <strong>resolve </strong>and state stays and will not be affected by any operations.</p><pre>var promise = new Promise(function(resolve, reject) {<br>  resolve(&#39;ok&#39;);<br>  throw new Error(&#39;not ok&#39;);<br>});<br>promise<br>  .then(function(value) { console.log(value) }) // ok<br>  .catch(function(error) { console.log(error) }); // not called</pre><h4>Promise.resolve and Promise.reject</h4><p>We can also call these two methods on Promise constructor with primitive values.</p><pre>Promise.resolve(&#39;foo&#39;);<br>new Promise(resolve =&gt; resolve(&#39;foo&#39;));</pre><pre>// above expressions are the same</pre><pre>Promise.reject(&#39;bar&#39;)<br>new Promise(reject =&gt; reject(&#39;bar&#39;));</pre><p>The executions will create a promise instance with state in resolved or rejected.</p><h4>Promise.all runs in series or parallel ?</h4><p>This puzzles a lot of people and I see this question is being asked by users on stackoverflow. Actually, all promise instances are already run by the time we call Promise.all with them.</p><pre>const p = Promise.all([delJSON(&#39;google.com&#39;), getJSON(&#39;baidu.com&#39;]);</pre><p>Recall I describe promise as a container that keeps the future result of operations earlier? Promise.all just waits until all promise are resolved and then pass the resolved values down to onResolved. So, strictly speaking, we cannot say Promise.all is either run in series or parallel.</p><p>That’s it, probably all you need to know Promise. For the sake of quick review, I list key points as follow.</p><ul><li>Three states : pending, resolved, rejected</li><li>Call Promise constructor with a function as the only one argument which takes resolve and reject two callbacks</li><li>For a successful/failed operation, call resolve with data or reject with error which will in turn trigger then or catch</li><li>Nested promise determines outside promise’s states</li><li>Use catch rather than onRejected for better error coverage</li><li>Call Promise.resolve or Promise.reject with primitive values will basically generate a new promise instance</li><li>Promise.all only cares about the state not in what order the promise are resolved</li><li>Use then().catch().then().catch() to handle errors in different operations</li></ul><p>Hopefully, I help you gain a better understanding of Promise.</p><p>Next, I will talk about using Async/Await in ES7.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a05a20bf4c53" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/everything-you-should-know-about-promise-a05a20bf4c53">Everything you should know about Promise</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>