<?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 Rajesh Babu on Medium]]></title>
        <description><![CDATA[Stories by Rajesh Babu on Medium]]></description>
        <link>https://medium.com/@rajeshdavid?source=rss-17f85189cad1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dk4GVL5DORk8OyceL7EzkA.png</url>
            <title>Stories by Rajesh Babu on Medium</title>
            <link>https://medium.com/@rajeshdavid?source=rss-17f85189cad1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:36:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajeshdavid/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[I am also onYoutube now !]]></title>
            <link>https://medium.com/@rajeshdavid/i-am-also-onyoutube-now-251c0207599d?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/251c0207599d</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[my-youtube-channel]]></category>
            <category><![CDATA[announcements]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Sat, 13 May 2023 19:12:00 GMT</pubDate>
            <atom:updated>2023-05-13T19:12:00.470Z</atom:updated>
            <content:encoded><![CDATA[<h3>I am also onYoutube now !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UX8CHXKplfpwXRgbN-VGGw.jpeg" /></figure><p>Hey followers, it has been an incredible 4-year journey with Medium, but from here on, I will post most of my content on youtube.</p><p>I will still post some of the articles here, but only if I find time apart from making my original content on youtube.</p><p>Feel free to subscribe to my channel, if you believe that you will find value there. If not, I will meet you with my next article.</p><p>Channel link <a href="https://www.youtube.com/channel/UCU2xH1a0ExxWXC4zk1VF_Eg">https://www.youtube.com/channel/UCU2xH1a0ExxWXC4zk1VF_Eg</a></p><p>Thanks for the love and it&#39;s much appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251c0207599d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code-splitting react-i18n locales using dynamic imports]]></title>
            <link>https://levelup.gitconnected.com/code-splitting-react-i18n-locales-using-dynamic-imports-97af247ad6f0?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/97af247ad6f0</guid>
            <category><![CDATA[i18next]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[codesplit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[internationalization]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 17:28:07 GMT</pubDate>
            <atom:updated>2022-07-11T11:23:15.188Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing internationalisation could be a daunting task for your frontend projects, but luckily tools like <a href="https://www.i18next.com/">i18n</a> make our lives easier by offering useful APIs that help us move forward quickly.</p><p><strong><em>Disclaimer</em></strong><em>: This article expects you to be already aware of some basic concepts around react, localization, webpack, and i18n.</em></p><p><strong><em>TLDR;</em></strong></p><p><a href="https://github.com/rajeshbabu-oviva/react-i18n-codesplitting-locales">GitHub - rajeshbabu-oviva/react-i18n-codesplitting-locales: A simple react-18n to code-split locale files using dynamic imports.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5t29_HeW6e4Smbctn_ooA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Mossholder</a> on <a href="https://unsplash.com/s/photos/split?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>General Architecture</h3><p>In a modern frontend application, we ideally have a core <em>CSV</em> from which we generate our <em>locale.json</em> files for each language we support. Assuming we support English, French and Japanese, then we would have three locale.json respectively.</p><p>If you are using a module bundler like webpack, the rudimentary implementation of the internationalization would involve importing all the locale.json files and bundling them all together in one bundle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbfMJ-Ag6XGQ5WNt6h-Ekw.png" /><figcaption>General Architecture</figcaption></figure><blockquote>The problem with this architecture is that your main.js bundle would have all the JSON files bundled together even when you do not need them.</blockquote><p>Imagine your app is being loaded for a single language, the JSON files for the other two languages are also part of your main.js bundle, although this might not be a problem for smaller applications, as your applications scale and the number of languages you support increases, then this rudimentary implementation would slowly eat up into your performance budgets.</p><p>Hence, a better solution would be to load only the required locale files or load them on demand. And this can be achieved via a concept called <a href="https://developer.mozilla.org/en-US/docs/Glossary/Code_splitting"><strong><em>Code-splitting</em></strong></a>.</p><h3>Code-splitting</h3><p>Code-splitting in a nutshell is the process of splitting up your code into smaller bundles based on certain criteria that consequently result in better load times.</p><p>Most modern bundlers like <a href="https://webpack.js.org/guides/code-splitting/#dynamic-imports">webpack</a>, come with their own configurations for code-splitting during build-time. There are multiple ways in which you can enforce your webpack configuration to split your code, but in our case, we are going to use <a href="https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import">dynamic imports</a>.</p><p>The following code-block when bundled with a modern bundler like webpack would generate a chunk for all the files in the <em>locales</em> directory and load them on demand based on the computed value of the variable <em>langKey</em>.</p><pre>async function loadResources(langKey) {<br>   const resources = await import(`./locales/${langKey}.json`);</pre><pre>   // do something with the resource.<br>}<br>loadResources().then(() =&gt; console.log(&#39;resource loaded dynamically&#39;));</pre><p>In this way, our architecture remains the same but the bundler would take care of splitting our application code into smaller chunks.</p><h3>Using Dynamic Imports With React-i18n</h3><p>Before we get into the demo of the actual code-base, let&#39;s look at how to implement the dynamic imports with <a href="https://react.i18next.com/legacy-v9/step-by-step-guide#2-lazy-loading-translations">react-i18n</a>. The official documentation recommends using a backend plugin, however, it can also be done easily with webpack as it supports dynamic imports out of the box.</p><p>When we use dynamic imports to load the file, we should be aware of race conditions between loading the resources and calling the <strong><em>useTranslation</em></strong> hook.</p><blockquote>The i18n init method should have been complete before we execute the useTranslation hook’s methods (eg: t(‘key’)).</blockquote><p>We can use <em>React.lazy</em> in combination with <em>Suspense</em> to await the dynamic imports before actually using the useTranslation <a href="https://github.com/rajeshbabu-oviva/react-i18n-codesplitting-locales/blob/master/src/App.tsx#L4">here</a>.</p><p>Alternatively, we can also use the <em>I18nProvider</em> to pass on the value of the i18n object, with <em>Suspense </em>to await the loading of the resources as shown <a href="https://github.com/rajeshbabu-oviva/react-i18n-codesplitting-locales/blob/master/src/AppWithI18nProvider.tsx">here</a>.</p><p>If the useTranslation hook is called earlier before the resources are available, you might end up with a warning of this sort —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hhkgKPwO-soJH6niPkapA.png" /><figcaption>Warning React-i18n</figcaption></figure><h3>Demo</h3><p>I bootstrapped my application quickly using this <a href="https://github.com/rajeshbabu-oviva/react-ts-boilerplate">boilerplate</a> that I built, based on the article I wrote <a href="https://medium.com/@rajeshdavid/a-quick-guide-to-choosing-a-robust-frontend-tech-stack-1f47c0458f08">here</a>.</p><h4>With Code-splitting</h4><p>Clone and open this <a href="https://github.com/rajeshbabu-oviva/react-i18n-codesplitting-locales">codebase</a> in your favourite editor, and follow the instructions on the read me to run the project. The code is currently code-split, how do you know?</p><p>Once you install and run the project using —</p><pre>npm run install<br>npm run serve<br>// visit http://localhost:3000/webpack-dev-server</pre><p>And you should see the following information about the current dev-server&#39;s dist directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABxM139JPpi7jgV1PP95Gw.png" /><figcaption>Webpack Dev-server Build Directory</figcaption></figure><p>And when you load the application initially and also switch the languages you should be able to see these chunks (<em>src_locales_ja_json.js</em> etc.,) downloaded from the network tab.</p><p>When we visit <a href="http://localhost:3000/"><em>http://localhost:3000</em></a><em>/?language=ja, </em>we only load the language JSON information meant for Japanese and not English and French.</p><blockquote>This is essentially code-splitting based on dynamic imports in action.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJMx6LHI6ljdXt7DyB_EXw.png" /><figcaption>Network Tab for Chunk Loading</figcaption></figure><p>Now that we see that the code-splitting is in action, let&#39;s see how the project fairs without code-splitting.</p><h4>Without Code-splitting</h4><p>Let&#39;s go ahead and modify our <a href="https://github.com/rajeshbabu-oviva/react-i18n-codesplitting-locales/blob/master/src/i18n.ts"><em>i18n.ts</em></a> file with the following code —</p><pre>import i18n from &#39;i18next&#39;;<br>import { initReactI18next } from &#39;react-i18next&#39;;<br>import en from &#39;./locales/en.json&#39;;<br>import fr from &#39;./locales/fr.json&#39;;<br>import ja from &#39;./locales/ja.json&#39;;</pre><pre>const LANG_KEY: string = new URLSearchParams(window?.location?.search).get(&#39;language&#39;) || &#39;en&#39;;</pre><pre>// eslint-disable-next-line @typescript-eslint/no-explicit-any<br>const resources: any = { en, fr, ja };</pre><pre>export const init = () =&gt; {<br>  i18n.use(initReactI18next).init(<br>   {<br>    resources,<br>    lng: LANG_KEY<br>   });<br>};</pre><pre>export default i18n;</pre><p>And visiting <a href="http://localhost:3000/webpack-dev-server"><em>http://localhost:3000/webpack-dev-server</em></a><em> </em>would give us the following result —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmOjpT62DFm0-sToUyfkwA.png" /><figcaption>Without Code-splitting</figcaption></figure><p>Here we can see that all our imported locale files have been bundled along with the main.js bundle, consequently increasing the bundle size of the same.</p><p>If you liked the article, please leave some claps and be sure to clone to code and play around with it.</p><p><a href="https://github.com/rajeshbabu-oviva/react-i18n-codesplitting-locales">GitHub - rajeshbabu-oviva/react-i18n-codesplitting-locales: A simple react-18n to code-split locale files using dynamic imports.</a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! More content in the <a href="https://levelup.gitconnected.com/">Level Up Coding publication</a>.<br>Follow: <a href="https://twitter.com/gitconnected">Twitter</a>, <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a>, <a href="https://newsletter.levelup.dev/">Newsletter</a><br><strong>Level Up is transforming tech recruiting ➡️ </strong><a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join our talent collective</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97af247ad6f0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/code-splitting-react-i18n-locales-using-dynamic-imports-97af247ad6f0">Code-splitting react-i18n locales using dynamic imports</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable and Modular Architecture for React-TS Applications]]></title>
            <link>https://levelup.gitconnected.com/building-a-scalable-and-modular-architecture-for-react-ts-applications-e1d917250e04?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d917250e04</guid>
            <category><![CDATA[modular-architecture]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Sat, 05 Mar 2022 14:15:33 GMT</pubDate>
            <atom:updated>2022-03-11T21:15:22.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>React.js is largely unopinionated, apart from some of the design patterns that are recommended and enforced while using hooks. And as a result, there is no official recommendation for organising your project and this most often times could lead to an architectural quagmire of components.</p><p>After experimenting with several different patterns and architectures at our current company, we finally ended up in a <strong><em>modular</em></strong> architecture that enabled us to scale our projects effortlessly.</p><h3>Core Principles</h3><h4>Isolation of Modules</h4><p>Every module needs to be isolated with its own dependencies and should be aware of all the dependencies it requires with an entry point for all its APIs.</p><h4>No-circular dependency</h4><p>Modules should not import each other as it breaks the <a href="https://en.wikipedia.org/wiki/Acyclic_dependencies_principle#:~:text=The%20acyclic%20dependencies%20principle%20(ADP,form%20a%20directed%20acyclic%20graph.">Acyclic-dependencies principle</a>.</p><h4>Differentiation between Modules</h4><p><em>Dependent vs Independent modules</em>. Independent modules are not so tightly coupled with other modules apart from common modules within the application, enabling us to out-source it to an external library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8eRI6PjUdn2q4tTEZ_MVQ.png" /><figcaption>Modular Architecture for React Applications</figcaption></figure><h3>Dependent Modules</h3><p>The modular architecture diagram represents a simple scalable modular architecture that adheres with our core principles.</p><blockquote><strong><em>Note</em></strong>: Every <strong>arrowhead </strong>in the diagram above<strong> </strong>represents an import statement.</blockquote><h4>Application</h4><p>The application/root module is simply the collection/composition of containers(a.k.a smart components). It&#39;s responsible for bootstrapping the application with <strong><em>react-suspense</em></strong><em>, </em><strong><em>error-boundaries</em></strong> and any top-level <strong><em>providers</em></strong>. In general, it should contain as very minimal code as possible.</p><h4><strong>Containers</strong></h4><p>The containers module is a collection of smart components that are connected to the state via the hooks. As you can see that the containers modules only import <em>common, components and hooks</em> modules and it doesn’t concern the state module at all. This helps us to scale the hooks module without affecting the states.</p><h4><strong>Hooks</strong></h4><p>The hooks module supplies data to the containers through the state and also updates the state based on the user interaction with the container components.</p><h4><em>State</em></h4><p>The state module is responsible for populating the client-side state using the service and common modules. This enables us to avoid polluting the containers and hooks with service APIs.</p><h3>Independent Modules (Possibly)</h3><p>Independent modules are only coupled to the <em>common modules</em>, although this is not as independent as we would like it to be, it&#39;s still easier to outsource it to an external library.</p><h4>Components</h4><p>The components module is just a collection of purely functional components that do not care about the application state.</p><p>Although this could be purely independent like an external library, you might still end up building <strong><em>application-specific components </em></strong>that closely resemble the data types from the common module. Hence it&#39;s often helpful to isolate/mark <em>generic</em> and <em>specific</em> components. <em>Generic </em>components do not use any types from the common modules, thereby enabling us to move them to an external component library.</p><h4>Services</h4><p>Services modules form the collection of APIs that interact with the backend and the resulting response should align with the core data types present in our common modules.</p><h3>Conclusion</h3><p>Each module represented in the diagram could be a folder of its own in your react-project, with an entry point<em>(eg: index.ts).</em></p><p><strong><em>And if done correctly every bubble could grow in size without affecting the other bubble.</em></strong></p><p>If you liked this article, please leave a clap. And let me know your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d917250e04" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-scalable-and-modular-architecture-for-react-ts-applications-e1d917250e04">Building a Scalable and Modular Architecture for React-TS Applications</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Guide To Choosing A Robust Frontend Tech Stack]]></title>
            <link>https://medium.com/@rajeshdavid/a-quick-guide-to-choosing-a-robust-frontend-tech-stack-1f47c0458f08?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f47c0458f08</guid>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[best-tech-stack]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 12:50:28 GMT</pubDate>
            <atom:updated>2022-01-13T13:54:39.296Z</atom:updated>
            <content:encoded><![CDATA[<p>At the time of writing this article, the frontend world is still a <em>wild west</em> of technologies and architectures. Although we have several approaches, frameworks, libraries, languages and environments at our disposal, not all of them are scalable and robust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wM9Ujw35xCpDKcHnu-YZnw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@tara-winstead?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Tara Winstead</a> from <a href="https://www.pexels.com/photo/red-check-mark-over-black-box-8850706/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Hence, we have to have some sense of awareness and responsibility while choosing a tech stack and this article is going to help with that.</p><h3>Choosing Core Technologies</h3><p>An application architecture consists of several parts that make our application meaningful, extensible and deployable. Whilst building a frontend architecture, it&#39;s of utmost importance to choose a <em>core library</em> and a <em>core language </em>before we choose the rest of the tech stack.</p><p>What do I mean by that?</p><p><strong>Core library or framework</strong> is the platform on which we are going to build our frontend applications, for example — <em>React, Vue, Angular and Svelte etc</em>.</p><p><strong>Core language,</strong> on the other hand, is the language that we are going to use to build it— namely <em>Javascript, Typescript and Coffeescript</em> <em>etc</em>.</p><p>All our additional development tools need to complement and work in unison with these two <em>entities/technologies</em>, if not, we are going to hit roadblocks down the line and it will also take a toll on our <em>developer-experience</em>.</p><p>There are several factors that are involved in choosing <em>core technologies</em>, but I ideally stick to 3 important ones —</p><ul><li><strong>Market Share</strong>— This enables us to find better developers from a large pool of skilled developers in that technology. <a href="https://2020.stateofjs.com/en-US/"><em>State Of JS</em></a> can give you a better understanding. <em>Eg:</em> At the time of writing this article, <em>React</em> still holds the largest market share.</li><li><strong>Opinionatedness</strong> — How <a href="https://stackoverflow.com/questions/802050/what-is-opinionated-software#:~:text=An%20opinionated%20framework%20is%20one,made%20by%20the%20framework%20designer."><em>opinionated</em></a> is the library/framework when you compare it to general web development. <em>Eg:</em> <em>React</em> is less opinionated than <em>Angular</em> and it offers a <a href="https://2014.jsconf.eu/speakers/sebastian-markbage-minimal-api-surface-area-learning-patterns-instead-of-frameworks.html"><em>minimal API surface</em></a>.</li><li><strong>Future Proof</strong> — How long can the code-base live without turning into <a href="https://www.sitepoint.com/write-maintainable-javascript/"><em>spaghetti</em></a>. This goes in hand-in-hand with <em>scalability</em> and the ability of the code to stay <em>standard</em> over time. <em>Eg:</em> <a href="https://www.monocubed.com/typescript-vs-javascript/"><em>Typescript</em></a> code-base scales better when working with larger teams.</li></ul><p>The choice of technology always comes with its own pros and cons, however to some degree,</p><blockquote>you have to be opinionated and intelligently biased towards the tools you use.</blockquote><h3>Building A Frontend Architecture</h3><p>With the above factors in mind, I have chosen the following core technologies<br> <strong>React</strong> — <em>Core library</em><br> <strong>Typescript</strong> — <em>Core language</em></p><p>The following illustration offers a simple perspective into building a simple yet scalable frontend architecture around our chosen core technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PZVIAX9paBBqoiDHP_57Q.png" /><figcaption>A Simple React-TS based Architecture.</figcaption></figure><h3>Finally — Our Tech Stack</h3><p>With the aforementioned architecture in mind, let’s take a quick look at the tech stack that could help us achieve it —</p><h4>Environment</h4><p><strong><em>node(v14+)</em></strong> and <strong><em>npm(v7+)</em></strong> — development and package <em>environment</em>.</p><h4>Core Libraries</h4><p><strong><em>react.js(v17+)</em></strong> — <em>core library</em> for the project.<br><strong><em>react-dom</em></strong><em> </em>— dom APIs for react.<br><strong><em>react-router-dom</em></strong><em> </em>— client-side routing for react.<br><strong><em>recoil </em></strong>— hooks based state-management for react. <br><strong> <em>react-hook-form</em></strong> — form library based on hooks. <br><strong><em>react-error-boundary</em></strong> — error boundary to catch rendering errors.</p><h4>Core Language</h4><p><strong><em>typescript(v4+)</em></strong> — <em>core language</em> used for development.</p><h4>Bundler</h4><p><strong><em>webpack(v5)</em></strong> — helps us <em>bundle</em> our project into single/multiple js chunks.<br><strong><em>webpack-cli </em></strong>— enables us to use the webpack command in the npm scripts.<br><strong><em>webpack-dev-server</em></strong> — enables us to run webpack development server.<br><strong><em>html-webpack-plugin</em></strong> — enables us to generate a final HTML using a template.<br><strong><em>fork-ts-checker-webpack-plugin</em> </strong>— enables us to type-check the code during the build process.<br><strong><em>eslint-webpack-plugin</em></strong><em> </em>— enables us to catch linting errors during the build process.<br><strong><em>clean-web-pack-plugin</em></strong> — enables us to clean existing build folders before the start of the build process.<br><strong><em>babel-loader</em></strong> — babel module loader for webpack.<br><strong><em>ts-node</em></strong> — helps node environment to run TS files.</p><h4>Transpiler</h4><p><strong><em>@babel/core(v7+)</em></strong> — helps us <em>transpile</em> our JS compatible with old browsers and new browsers with its support libraries — <br><strong><em>@babel/preset-react</em></strong> — enables us to use the latest JS features and will also use <em>browserslist</em> from <em>package.json</em> while transpiling code for the target browsers.<br>@<strong><em>babel/preset-react</em></strong> and @<strong><em>babel/preset-typescript </em></strong>— enables us to transform React and Typescript code into JS.<br><strong><em>@babel/plugin-transform-runtime</em></strong><em> </em>— enables us to save on code size, remove some duplicates in our code, and add polyfills where required.<br><strong><em>@babel/runtime-corejs3</em></strong><em> </em>— runtime corejs polyfills on production bundle.</p><h4>Linter</h4><p><strong><em>eslint(v7+)</em></strong> — <em>linter</em> for our ecmascript.<br><strong><em>eslint-config-prettier </em></strong>— turns off all rules that are unnecessary or might conflict with prettier.<br><strong><em>eslint-plugin-prettier</em></strong> — runs prettier as an eslint rule and reports differences as individual eslint issues.<br><strong><em>eslint-plugin-react</em></strong> — runs react specific eslint rules.<br><strong><em>eslint-plugin-react-hooks </em></strong>— runs react hooks rules for eslint.<br><strong><em>@typescript-eslint/eslint-plugin</em></strong> — enables eslint for TS code.<br><strong><em>@typescript-eslint/parser </em></strong>— enables parsing of TS.</p><h4>Formatter</h4><p><strong><em>prettier(v2+)</em></strong> — <em>formatter</em> that works with eslint plugins.</p><h4>Test Environment</h4><p><strong><em>jest</em></strong> — test environment to build and run our unit and snapshot tests.<br><strong><em>@testing-library/react</em></strong> — complete React DOM testing utilities.<br><strong><em>@testing-library/dom </em></strong>— simple and complete DOM testing utilities.<br><strong><em>@testing-library/jest-dom</em></strong> — custom jest matchers to test the state of the DOM.<br><strong><em>@testing-library/user-event</em></strong> — fires user events for our test cases.</p><h4>Internationalization</h4><p><strong><em>i18next</em></strong> — internationalization framework for JS.<br><strong><em>i18next-browser-languagedetector </em></strong>— helps us detect browser language.<br><strong><em>react-i18next </em></strong>— internationalization APIs for react.</p><h4>Component Library</h4><p><strong><em>@chakra-ui/react </em>— </strong>component library helper to build reusable components.<strong><br><em>@emotion/react — </em></strong><em>css-in-js</em> library for react.<strong><em><br></em>@emotion/styled — </strong>styled APIs for emotion-based react components.<strong><br>@framer-motion</strong> — animation library for react.<br><strong><em>@chakra/icons</em></strong> — icon package for chakra-ui.</p><h3>Conclusion</h3><p>In this <em>tech-stack</em> above not all of them are production <em>dependencies</em>, only some are, for example — react, its supporting libraries, internationalization, chakra-ui and @babel/runtime-corejs3 are dependencies. And everything else is a <a href="https://medium.com/@dylanavery720/npmmmm-1-dev-dependencies-dependencies-8931c2583b0c#:~:text=The%20difference%20between%20these%20two,are%20also%20required%20at%20runtime."><em>development dependency</em></a>.</p><p>Hopefully, this quick guide enables you to build your tech stack for your next project.</p><p>Leave a clap or 50, if you liked it. Feel free to leave comments!</p><p>And check out the <a href="https://github.com/rajeshbabu-oviva/react-ts-boilerplate/tree/feature/project-setup"><strong><em>GitHub branch</em></strong></a> for the code.</p><p>Happy Coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f47c0458f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does a graphQL service work internally?]]></title>
            <link>https://codeburst.io/how-does-a-graphql-service-work-internally-496dc9264096?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/496dc9264096</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql-apollo-server]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Fri, 15 May 2020 13:29:41 GMT</pubDate>
            <atom:updated>2022-08-25T09:08:40.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>How does graphQL work anyway?</h3><h3>Introduction</h3><p>Have you ever wondered how graphQL selectively returns only the data that you specifically requested?</p><figure><img alt="A connected web of nodes and nylon ropes." src="https://cdn-images-1.medium.com/max/1024/1*3hdPHh81PA_7EXLN6KPRhg.jpeg" /><figcaption>Interconnected Nodes — Photo by <a href="https://unsplash.com/@clintadair?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clint Adair</a> on <a href="https://unsplash.com/s/photos/connections?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>GraphQL is language-agnostic. And it is more of a concept that can be implemented in any of the supporting languages such as Ruby, Java or Python based on the official <em>specifications</em>. However, in reality, the graphQL implementation, the developer community, and the tooling around the Javascript language is more robust and mature compared to all the other languages. That being said, Javascript/Typescript could be a better language to work with, to get the best out of a lot of available graphQL toolings.</p><h3>Motivation</h3><p>To break down the core concepts behind graphQL with the help of <em>graphQL.js </em>by walking through <em>a simple graphQL implementation.</em></p><h3>GraphQL Service Overview</h3><p>In a simple graphQL service, the incoming query is parsed, and the query fields are executed and resolved against the schema to produce the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ilUAJ31T7cY4OgHtOMZ-Q.png" /><figcaption>GraphQL Service Overview</figcaption></figure><h3>Building a GraphQL Service</h3><p>The first step into building and running a graphQL service is to define and build your schema. A schema holds the complete data type and also the data structure information. The schema can be represented in two ways:</p><ol><li>SDL<em>(Schema Definition Language)</em> representation.</li><li>GraphQLSchema object-based representation.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0846928f5eeccfd07d30ac3fd07f00f0/href">https://medium.com/media/0846928f5eeccfd07d30ac3fd07f00f0/href</a></iframe><h4>Schema Representation and Conversion</h4><p>In an ideal world, a graphQL schema is usually represented in the form of an SDL because it makes the schema more human-readable, but in order for the JS environment to understand and execute the SDL as a Javascript code, the SDL schema needs to be converted into an equivalent GraphQLSchema object.</p><p>For example, this is the SDL representation of a simple schema:</p><pre><strong>#SDL Representation of Schema</strong><br>type Person {<br>  name: String<br>  address: String<br>}</pre><pre>type Query {<br>  person(id: ID): Person<br>}</pre><p>The equivalent executable GraphQLSchema object representation of the SDL above would be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOlC1_Nc62F7ccJfyZDGow.png" /><figcaption>Executable GraphQLSchema Object Representation</figcaption></figure><blockquote>The graphQL.js’s <strong>buildSchema </strong>method can convert <strong>SDL schema to GraphQLSchema</strong> <strong>object</strong> representation. Conversly, <strong>printSchema </strong>converts<strong> GraphQLSchema object </strong>back to<strong> SDL schema</strong>.</blockquote><p>The process of converting an SDL schema into a GraphQLSchema object using the buildSchema method comes with a caveat, once built there will be no resolvers attached to the converted GraphQLSchema object because the SDL schema doesn’t have any knowledge of the resolvers, thereby making the GraphQLSchema object non-executable.</p><p>There are two ways to make your GraphQLSchema object executable.</p><blockquote>i) Either you can create your own executable GraphQLSchema object, with resolver methods as shown in the image above.</blockquote><blockquote>ii) or you can automate the process by using <a href="https://www.apollographql.com/docs/graphql-tools/generate-schema/">graphQL-tools</a> to combine your typeDefs(SDL) and resolvers together into an executable GraphQLSchema object.</blockquote><p>It is also important to keep in mind that the GraphQLSchema constructor doesn’t accept any random type object, in fact, all your types should be constructed first before being used to build the schema. In our case, you can see that we have built a <strong><em>PersonType</em></strong> which is constructed from <strong><em>GraphQLObjectType</em></strong> class. In a similar fashion, you can also construct other <a href="https://graphql.org/graphql-js/type/#graphqlschema"><em>types</em></a> based on their respective class definitions.</p><h3>Running a GraphQL Service</h3><p>A valid executable schema is all that you need to run a graphQL service and start listening to the incoming query requests. The entire process of accepting incoming queries and resolving them involves the following steps —</p><ul><li><strong>GraphQL Query Parsing</strong></li><li><strong>GraphQL Query and Schema Validation</strong></li><li><strong>GraphQL Query Execution</strong></li></ul><h3>GraphQL Query Parsing</h3><p>The incoming query also comes in a uniquely formatted string which needs to be parsed into a meaningful data-set or a tree (AST) based on graphQL <a href="http://spec.graphql.org/June2018"><em>specifications</em></a><em>, </em>before they are executed.</p><blockquote><em>GraphQL requires every incoming query field to be resolved separately and it achieves that through the power of ASTs.</em></blockquote><h4>Abstract Syntax Trees (ASTs)</h4><p>ASTs are the core of any graphQL operation. ASTs are nothing but huge JSON trees/objects that are created and managed by AST conversion methods present inside the graphQL.js.</p><p>In the code sample below, you can see that we have an incoming graphQL query and the <strong><em>parse</em></strong> method converts the incoming query into an AST for the graphQL execution method to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Myqhs_cH5mMCy1ldyYi7pA.png" /><figcaption>Parsing Incoming Query into an Operation Definition AST</figcaption></figure><blockquote>Just a heads-up, the schemas are also converted to AST and are available to us inside the <strong>info</strong> argument of the resolvers, however, is not important at this point.</blockquote><h4>Difference between Query AST and Schema AST</h4><p>Again, this AST is not language-specific or tied to any specific algorithm, anyone can build their custom AST based on their specification sheet and requirements.</p><p>A good place to verify the corresponding ASTs for your schemas and queries can be done here on the <a href="https://astexplorer.net/"><strong><em>ASTExplorer</em></strong></a> website, where you can switch to the graphQL.js section to test the JSON object for your corresponding schema and queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*s3-CAp250gg6fCwPL20eBg.png" /><figcaption>Difference between Query AST and Schema AST</figcaption></figure><p>On the left side, you can see that we have a schema represented in form of SDL and a corresponding Query Definition for the schema. And on the right side, you can see that we have an AST tree with two different types of objects with the name <em>OperationDefinition</em> and <em>ObjectTypeDefinition</em>. In fact, these two objects are meant to represent two different ASTs.</p><blockquote>The Query-Definition when converted into a AST returns the Operation-Defintion Tree, whereas the Schema-Definition returns the ObjectType-Defintion Tree.</blockquote><p>This difference is based on the internal graphQL specifications and the AST conversion algorithms present inside the graphQL.js. For basic query executions, we only need to be concerned about the <strong><em>Query Definition’s AST conversion (queryAST)</em></strong>.</p><h3>GraphQL Query And Schema Validation</h3><p>Once we have parsed our incoming query into a queryAST. The queryAST is ready for <strong><em>validation and execution </em></strong>against the schema. Although technically, you can execute the query even if only some fields are valid and others not, graphQL explicitly recommends validating query and schema before execution. You can read further on the <a href="http://spec.graphql.org/June2018/#sec-Validation"><em>validation</em></a> specification from graphQL.</p><p>The validation process validates both the schema and the query for duplicate field names, ambiguous fields and other discrepancies. The validation process also validates the schema to see if it contains only the allowed graphQL Type Definitions.</p><p>The validator runs through the queryAST and schema and checks the validity<em> </em>of the <em>Document, Operations, Fields, Arguments, Variables, Fragments, Directives and Values</em>. The validation specification is explained in <a href="http://spec.graphql.org/June2018/#sec-Validation">detail</a> with proper examples of how each element is validated based on a set of rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKSEBsJQK7U7xbee25Fo1g.png" /><figcaption>Validate Method from GraphQL.js</figcaption></figure><p>Although tools like Apollo Server’s <em>graphQL playground</em> automate the validation process for you, it still helps to have a better understanding of the manual validation process.</p><h3>GraphQL Query Execution 🤯</h3><p>Once the query is validated without any errors, it’s ready for execution. In order to better understand the execution process I played around with the source code of the graphQL.js and cross-checked the code execution with the graphQL specification sheet for <a href="http://spec.graphql.org/June2018/#sec-Execution"><strong><em>execution</em></strong></a>, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VU7rt1uS_4Nc8jv15X4vnQ.png" /><figcaption>Query Execution Flow Diagram</figcaption></figure><p>Based on the flow diagram above, let&#39;s look at the query execution process step by step:</p><h4><strong><em>Assertion Process</em></strong></h4><p>The first step in the execution is the assertion process that quickly validates the <a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L75"><em>schema</em></a><em>, </em><a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L93"><em>queryAST</em></a> and the <em>variables(if they are passed into </em><a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L104"><em>execute</em></a><em> method)</em>. Although the validation process runs in the previous step, graphQL runs it again in case you have not manually validated the schema yourself. The execution process breaks if it encounters any errors.</p><h4><strong><em>Building the Execution Context</em></strong></h4><p>Once the assertion is complete, the graphQL.js starts building the execution context. During this process, it collects all the required details for the execution such as <em>fragments, operation type </em>from the queryAST<em> </em>and also <em>coerces the </em><a href="https://graphql.org/learn/queries/#variables"><em>variable values</em></a><em> </em>if they are present.</p><p>Coercion in graphQL.js is similar to Javascript’s coercion but it works based on its own pre-defined set of graphQL <a href="http://spec.graphql.org/June2018/#sec-Scalars">scalars</a> specifications.</p><p>The built execution context consists of <em>schema, fragments, root value, context value, operation definition, coerced variable values, fieldResolver and errors</em>.<strong><em> </em></strong>For a simple query such as ours, all we need to worry about is the <em>schema</em> and the <em>operation definition</em> from the queryAST.</p><h4><strong><em>Execution Operation</em></strong></h4><p>The execution operation is the entry point where the <em>field execution</em> starts executing all the requested fields from the incoming query.</p><pre><strong>//Incoming Query</strong><br>{  <br>  person(id: &quot;123&quot;) {<br>     id    <br>     name    <br>     address {<br>       street<br>       city    <br>     }  <br>   }<br>}</pre><p>To kick off the query execution this step prepares two important entities to be passed on to the <em>field-execution</em> step:</p><p>i) The first one is the <strong>parent-type</strong> of the current executing field. For example, if we are executing the <em>person</em> field in the incoming query represented above, then the <a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L59"><em>QueryType</em></a> is regarded as the parent-type for this field. Similarly, if we are executing the <em>id</em> field then <a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L44"><em>PersonType</em></a><em> </em>is considered to be the field’s parent-type.</p><p><em>ii) </em>The next one is the <strong>array of field-nodes</strong> that are collected from the SelectionSet’s selections of the queryAST’s OperationDefinition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OClSDpDy3A_813CR7enHwQ.png" /><figcaption>OperationDefinition of the QueryAST</figcaption></figure><h4><strong><em>Field Execution</em></strong></h4><p>Once the <strong>array of field nodes</strong> and the <strong>parent-type</strong> information are available for the field then it means that the field is ready for execution. In this step, the array of field nodes are iterated over and the corresponding field names are extracted. These extracted fields-names look up the parent-type for their respective field definitions.</p><p>In our case, the <em>person</em> is the first field to be executed and the <em>person</em> field-name would look up it&#39;s parent-type i.e <em>the</em> <a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L59"><em>QueryType</em></a><em> </em>for extracting its <em>field definition</em>. The field definition consists of all the required information about the field including <em>type, arguments </em>and<em> the resolver</em>. This field definition is passed on to the next step for resolution.</p><h4><strong><em>Field Resolution</em></strong></h4><p>This operation receives the field definition from the <em>field-execution</em> step. First, the arguments in the field-definition object are coerced. Then the resolver method from the field definition is called with or without the coerced arguments. If there is no resolver method found on the field definition, then a built-in <strong><em>default-resolver</em></strong> would be called in its place. Finally, the result of the resolver execution is passed on to the <em>value-completion</em> step for further execution.</p><blockquote>A <strong>default-resolver</strong> is nothing but a method that returns the field-name from the previously executed result or parent argument of the resolver method.</blockquote><p>If we consider our example incoming query above, graphQL.js during resolution of the <em>person</em> field would first coerce its <em>id</em> argument’s value(“123”) and then would call the <a href="https://gist.github.com/rajeshbabu-oviva/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L67"><em>resolver</em></a> method to return the result for <em>value-completion</em>.</p><h4><strong><em>Value Completion (recursive)</em></strong></h4><p>This last step is important because it’s when graphQL decides to either carry out a recursive field execution or store the result. Once the resolved result is obtained for the current executing field from the <em>field-resolution </em>step, graphQL.js then checks to see whether the corresponding field-definition type is an instance of <strong><em>GraphQLObjectType</em></strong><em>.</em></p><p>If the current field-definition type is an instance of <em>GraphQLObjectType</em>, it means that the resolved result is an object with fields. And as we know that graphQL requires each incoming query field to be resolved separately, the <strong><em>field-execution process is initiated again</em></strong> for the execution of the current field’s sub-fields and the current field’s field-definition type is passed as<strong> </strong>the<strong> parent-type</strong>, along with the <strong>field-nodes array </strong>from the SelectionSet’s selections of the current field-node.</p><p>For example, if the <em>person</em> field returns a resolved result of <strong><em>{id: 1, name: ‘raj’, address {street: ‘one’, city: ‘berlin’}}</em></strong>, then to resolve <em>id, name </em>and<em> address </em>fields respectively, the <em>field-execution</em> is initiated again, with <a href="https://gist.github.com/rajeshdavidbabu/d8eabd1b83e6638115d8b3be5ecce2cd#file-index-js-L44"><em>PersonType</em></a> as the <strong>parent-type</strong> and the <strong>field-nodes array</strong> from the SelectionSet’s selections of the <em>person</em> field-node<em>(refer the Field Execution sub-heading).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4btOhMpN5B2We_2geLPJ9A.png" /><figcaption>Person Field Node from QueryAST</figcaption></figure><p>If the current field definition is not at an instance of <strong><em>GraphQLObjectType </em></strong>but<strong> </strong>an instance of <strong><em>GraphQLScalarType</em></strong>, then the resolved result is collected and stored in an object under the current<em> field-node name </em>as its key. This ensures that the resulting data returned for the query maintains the same order as the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*tsBGn5By3jYtR6fCn2xesw.jpeg" /><figcaption>Input Query with the Output Response</figcaption></figure><p>The recursive <em>field execution</em> process continues until all the fields are resolved up until the points where all the final values are <em>scalar</em> types. The resulting object is then returned if there are no promises found in the resolution result, but if it contains any promises then a promise object is returned which is later resolved into the resulting object, thereby ensuring both <em>synchronous</em> and <em>asynchronous</em> resolver methods can be used.</p><p><strong><em>Note: </em></strong>This process is explained for query execution and it&#39;s more or less identical for both mutations and subscriptions with some caveats. For mutations, the field execution happens serially, which means the field-resolution happens one after the other, whereas for queries it happens in parallel, where two or more sibling fields can resolve in any order.</p><h3>Conclusion</h3><p>This could be overwhelming at first glance, but once you run the gist locally and start debugging the code, you will gain a better understanding of the entire process.</p><p><em>If you liked this article please leave some claps to show your support. If you have a hard time running the gist, you can always clone the repo below. I would also like to thank my friend and colleague Adrian Rivers for proofreading and improving the post.</em></p><p><a href="https://github.com/rajeshdavidbabu/simple-graphql-execution">rajeshdavidbabu/simple-graphql-execution</a></p><h3>Further Reading</h3><blockquote><a href="https://medium.com/@weblab_tech/graphql-everything-you-need-to-know-58756ff253d8">Everything you need to know about graphQL (good comparison with REST</a>).</blockquote><blockquote><a href="https://graphql.org/graphql-js/">GraphQL.js official website</a>.</blockquote><blockquote><a href="https://hackernoon.com/everything-you-need-to-know-about-graphql-a5bc3622e54">A detailed hackernoon article about graphQL</a>.</blockquote><blockquote>If you have plenty of time at your hand complete the full-stack tutorial at the <a href="https://www.howtographql.com/">how-to-graphQL website</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=496dc9264096" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/how-does-a-graphql-service-work-internally-496dc9264096">How does a graphQL service work internally?</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 built a Node.js Service to Clone my AWS S3 Buckets]]></title>
            <link>https://medium.com/bitsrc/a-practical-guide-to-building-a-node-js-service-on-an-aws-s3-bucket-aff19105ba83?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff19105ba83</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 15:22:07 GMT</pubDate>
            <atom:updated>2019-03-07T15:34:12.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pNMMZbTGFovZSlL9b10ew.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/4AG-k7KeNOg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Malte Wingen</a> on <a href="https://unsplash.com/search/photos/node-js?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>TL;DR</strong> — <em>Get straight to the code !!!</em></p><p><a href="https://github.com/rajeshdavidbabu/Node-Clone-S3-Bucket">rajeshdavidbabu/Node-Clone-S3-Bucket</a></p><h3>Introduction</h3><h4>Node.js</h4><p>Node.js has been in the market for quite some time, as a Javascript developer, it is only fair that you learn how it works by now. Contrary to popular frontend developer’s belief, Node.js is not a library, instead, its an eco-system or more so like a platform on which you can run Javascript and the best part is that you get access to various <em>I/O operations</em>.</p><blockquote>All the frontend javascript runs on the browser with the help of V8 and the browser environment itself, likewise, Node.js involves a V8 engine and Libuv.</blockquote><blockquote>If you are an absolute starter on Node.js, please go through this write-up to get an overall understanding of <a href="https://codeburst.io/the-only-nodejs-introduction-youll-ever-need-d969a47ef219"><strong><em>why and how to Node.js</em></strong></a><strong><em>?</em></strong></blockquote><p>Since this write-up is about building a fully-functional Node.js application, we would not go deep into the basics and quickly touch upon the key points to look out for and also a bit of insight into the application itself.</p><h4>AWS (Amazon Web Services)</h4><blockquote>AWS is a cloud-based eco-system where you can manage the whole infrastructure of your applications without needing any physical hardware or server.</blockquote><p>In short, AWS offers a wide range of solutions for companies seeking to store data, access data, run servers, scale their existing services and much more. Out of these services, one of the most important and simplest service is S3(Simple Storage Service). The S3 not only offers block-storage space, meaning that you can store any file format on it but also comes with a set of REST APIs through which you can make CRUD operations.</p><p><em>These two technologies mentioned above, make a powerful combination in the industry for various use cases when your Node.js application needs to randomly store and retrieve files, store executables or any other data format that is not supported by an ACID complaint DB such as SQL DBs. In short, it’s a file storage system where you can store any type of data and easily access them.</em></p><h3>What’s this project about?</h3><blockquote><strong><em>This project is basically building a Node.js application to clone your S3 bucket locally and recursively.</em></strong></blockquote><p><em>TBH, this project is a one-liner using the AWS-CLI. Yes, you heard it right. So why are we doing it anyway?</em></p><p><strong><em>“Why should all the problems must always have only one solution? I simply like more than one. Be it good or bad”</em></strong></p><p>Let’s look at the existing solution first. You install the AWS-CLI and run the following command:</p><pre>aws s3 cp s3://my-s3-bucket/ ./ --recursive</pre><blockquote><strong><em>S</em>urprisingly, apart from using the AWS CLI, I didn&#39;t find any proper Node.js script or an app that would do this for medium to large scale buckets using the AWS-SDK. The answers I found on Node.js posts online had several problems, including half-baked scripts, scripts that would try and synchronously create a file and would not know when to complete and also would ignore cloning empty folders if there was any. Basically, it didn&#39;t do the job right. Hence decided to write one myself, properly.</strong></blockquote><p>I am positive that this would give you a better understanding of how a Node.js application should look and feel, in spite of its size and operation.</p><h3>What can you expect out of this writeup?</h3><p>As I said above, I am not gonna explain the code line-by-line, as I am posting the entire base out. Instead, I will talk about how I have architected the application, with a bit of insight into the core-logic and key features. Let me list out what you can expect and get an idea by the end of this write-up.</p><ul><li><strong><em>Project Structure of our Application</em></strong></li><li><strong><em>Core Logic Surrounding the Application</em></strong></li><li><strong><em>Streams in Node.js to Download a File</em></strong></li><li><strong><em>Using AWS-SDK to access S3 APIs</em></strong></li><li><strong><em>Entire Codebase</em></strong></li></ul><h3>Before we start</h3><p>Before we jump the guns, let’s ask why do we call this a service and not a server. I call this a service because it just does one job and no external entities are sending requests to our running service, if they were to send the request to our application, then I would probably call this a server if it’s listening on a port.</p><blockquote>When I was a junior frontend developer, I always thought that Node.js applications were made only of a single server file and thought that the code would always be messy, while that is true to some extent, I later learnt that that’s not how it should be. As a responsible developer, we should always aim to keep the files as small as possible and separate the concerns properly. That’s the key to developing a scalable Node.js application.</blockquote><h3>Project Structure</h3><p>There is no opinionated approach for building the project structure, it can change from project to project based on the use case. Personally, I split them into smaller independent modules. One module does one type of task and one type of task only.</p><blockquote>Let’s say, if I have a <strong><em>network.js </em></strong>file<strong><em>, </em></strong>it does only network operations and doesn’t modify the file structure or create a new file.</blockquote><p>Let’s look at our project structure for instance,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00Gb_2AuNJuQe_nJ2tK_Nw.png" /><figcaption>Project Structure</figcaption></figure><p>As I said before, there is no particular way to structure your project but its ideal to pick a topic and group all your files under that topic. For me, it was activity, <strong><em>“what does that file handle and how ?”.</em></strong></p><p>Let’s start from the root and go step by step.</p><h4>Application Dependencies</h4><p>These are project dependencies and are essential for development and deployment. And are mostly straight forward to understand:</p><ul><li><em>package.json</em></li><li><em>index.js</em></li><li><em>git ignore/eslint configs</em></li><li><em>license, readme etc.</em></li><li><em>node_modules</em></li></ul><p>And then comes the <strong><em>config</em></strong> file, the <strong><em>config</em></strong> file consists of all your application config, api_keys, bucket name, target directory, third_party links etc., normally we would have two config files one for <em>production</em> and one for the <em>development</em> environment.</p><h4>Core Entities</h4><p>Once we made the skeleton of the application ready with the application dependencies, then we have the core entities. In our application, the Core entities include Handler, Service and Storage.</p><blockquote><strong><em>Handler </em></strong>is where we glue the entire application and create Services, Storages and inject required dependencies and expose an API for the index.js to handle.</blockquote><blockquote><strong><em>Service </em></strong>is where our core-logic of the application lives and all the jobs to other dependencies are delegated from here.</blockquote><blockquote><strong><em>Storage </em></strong>is where all our storage operations take place. In our application S3 is the external storage from where we retrieve our files and data from, hence the AWS-SDK operations exclusively happen only inside this storage module.</blockquote><h4>Helpers and Utils</h4><p>When the service starts to run it needs to do all the intended tasks at the same time. For example, in our application, once we get the list of contents under a directory, we need to start creating/cloning the contents locally. This operation is delegated to <strong><em>cloner.js</em></strong>, a helper which is only responsible for cloning the files and folders. The cloner, in turn, needs to access the <strong><em>fileOps.js</em></strong> module to create directories and files.</p><blockquote>Under helpers, we have the following files doing their respective chores with or without the help of other helpers.</blockquote><blockquote><strong><em>Cloner</em></strong>, handles the cloning of the files and directories with the help of <strong><em>fileOps</em></strong> module.</blockquote><blockquote><strong><em>Data Handler</em></strong>, maps and parses the data from S3 bucket into a usable or consumable data by the service.</blockquote><blockquote><strong><em>Downloader</em></strong>, only downloads files from S3 bucket and pipes the operation to a write-stream or simply put, takes care of downloading files asynchronously.</blockquote><blockquote><strong><em>fileOps</em></strong>, as the name suggests, uses Node’s <strong>fs</strong> module to create file-streams and directories.</blockquote><blockquote><strong><em>filePath</em></strong> provides the entire application with the target folder for cloning the S3 bucket’s files and directories and also returns the target bucket and target root directory on the S3.</blockquote><blockquote><strong><em>Logger</em></strong> <em>inside utils returns an instance of Bunyan logger which can be used to send logs to third parties like Kibana.</em></blockquote><h3>Core Logic Surrounding the Application</h3><p>Now that we have done our project setup, let’s look into the core logic of the <strong><em>service</em></strong> module. It involves the sequence of the following actions:</p><ul><li><strong><em>Fetch the list of Keys from the bucket and the target Prefix. </em></strong><em>(check AWS-SDK Javascript APIs)</em></li><li><strong><em>Separate the files and directories, because we clone the directories and download the files.</em></strong></li><li><strong><em>Clone all the directories first, and then move on to download the files.</em></strong></li><li><strong><em>Download the files through streams and log success and failure respectively. </em></strong><em>(AWS-SDK ListKeys API response sometimes ignores giving out directory Keys, hence we need to check for if a directory exists, if not present we create one before downloading the contained file)</em></li></ul><blockquote>Additionally, the service not only clones the entire bucket but also clones only specific folders, without losing the folder tree structure, based on our Prefix configuration as specified <a href="https://github.com/rajeshdavidbabu/Node-Clone-S3-Bucket#configuration">here</a> as the rootDirectory for cloning.</blockquote><h3>Downloading Files Using Streams</h3><p>Another important concept around the Node.js is using streams to upload and retrieve data from an external source. In our project, the external source is the AWS S3.</p><blockquote>When downloading the files we create a read stream from the AWS SDK getObject method and pipe it to a writeStream which will close automatically once all the data is written. The advantage of using streams is the memory consumption, where the application doesn’t care about the size of the file downloaded.</blockquote><p>Our code inside <strong><em>storage </em></strong>module<strong><em> </em></strong>as shown below uses streams to asynchronously download the data without blocking the event loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiO9-odlUOi1HgG-wcSd6w.png" /><figcaption>Node.js streams with AWS getObject</figcaption></figure><p>To dig deeper into Node.js streams, please refer to this write up <a href="https://medium.freecodecamp.org/node-js-streams-everything-you-need-to-know-c9141306be93">here</a>.</p><h3>Using AWS SDK to access S3</h3><p>This is the most straight forward topic in the whole application, where you install the <strong><em>AWS-SDK</em></strong> and start accessing the methods in it. Taking a look at the <strong><em>storage</em></strong> file would give you a better understanding of how to import and call methods on the same.</p><h3>The Codebase of the Application.</h3><p>Here you can find the entire code for this application, more than reading this, hands-on would give a great deal of information and help you understand the core concepts of this application. Feel free to fork it, play with it and if you like it leave a star on the repo.</p><p><a href="https://github.com/rajeshdavidbabu/Node-Clone-S3-Bucket">rajeshdavidbabu/Node-Clone-S3-Bucket</a></p><h3>Conclusion</h3><p>This marks the end of this write-up, hope it gave a better understanding of how to plan, build and run a Node.js service in the real-time on a platform such as AWS. Feel free to leave your comments, responses and not to mention claps on the story if you liked it. Thanks for reading and feel free to comment!</p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/5-tools-for-faster-development-in-react-676f134050f2">5 Tools for Faster Development in React</a></li><li><a href="https://blog.bitsrc.io/monorepo-architecture-simplified-with-bit-and-npm-b1354be62870">Monorepos Made Simpler with Bit</a></li><li><a href="https://blog.bitsrc.io/11-javascript-animation-libraries-for-2018-9d7ac93a2c59">11 JavaScript Animation Libraries For 2019</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff19105ba83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/a-practical-guide-to-building-a-node-js-service-on-an-aws-s3-bucket-aff19105ba83">How I built a Node.js Service to Clone my AWS S3 Buckets</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Promises: An In-Depth API Guide]]></title>
            <link>https://codeburst.io/playing-with-javascript-promises-a-comprehensive-approach-25ab752c78c3?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/25ab752c78c3</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async-functions]]></category>
            <category><![CDATA[es6-in-depth]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 16:52:26 GMT</pubDate>
            <atom:updated>2023-03-29T15:30:40.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGiiqgFwaDq5eNHII17Lvw.png" /></figure><p>“Write down the syntax for promises on this sheet of paper”, is enough to give nightmares to a lot of junior and even mid-level javascript developers. I have seen people going blank and sit for minutes together trying to put their mind around creating a simple promise and a callback.</p><p>I am sure you would have read many articles about promises, but I promise (<em>pun intended..</em>) you that this one will show you the parts which you have missed. With no time to waste, let’s jump in.</p><p>P.S: If you know the basics just skip to the sub-heading called <strong><em>‘Promises with multiple then methods’ </em></strong>or if you are an expert jump to<em> </em><strong><em>‘Order of execution of promise blocks’</em></strong>, you might see some surprises there.!!</p><h3>Definition</h3><blockquote>Let’s keep the books and docs away for some time and put things in perspective. Promises are basically javascript objects used asynchronously.</blockquote><p>In a synchronous execution, you don’t need states, per se. Your code either successfully execute or fail to execute. In asynchronous code, we execute, wait for callbacks and decide if its success or failure and continue with the synchronous code execution.</p><p>On the same lines promises have three states:</p><p><strong><em>Pending, Resolved and Rejected.(I am sure the names are self-explanatory here).</em></strong></p><h4><strong>Pending:</strong></h4><p>Every promise created remains <strong>indefinitely</strong> in a pending state, unless it resolved or rejected. Period.!! This is the absolute truth. No arguing with it.</p><h4>Resolved:</h4><p>When the promise’s resolve method is called the promise takes up a resolved state. Resolve is essential for a promise to move on to execute its then method.</p><h4>Rejected:</h4><p>As the name suggests the promise moves on to rejected state from pending state if its rejected. And goes on to execute the catch method, where you can extract the error if there is any.</p><h3>Syntax</h3><p>Since we have moved on from ES5 to ES6, I am just gonna straightaway use the ES6 Syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYL8yJd8e8V8y7HZyYU4IA.png" /><figcaption>Basic Promises Syntax</figcaption></figure><blockquote><strong>Note:</strong> Here, the then method accepts both resolved and rejected callbacks, but catch accepts only rejected callbacks. In practice, always use the <strong>then</strong> method for handling resolved callbacks and <strong>catch</strong> for rejections to keep things cleaner and for proper funnelling of errors at a single exit point.</blockquote><p>This syntax is pretty clean in ES6 than in ES5. I vaguely, remember mixing resolve and reject in the same then method, resulting in some very ugly and unreadable code. So, now we know how the syntax works in Promises. Let’s jump into different ways of using promises and unravel the secrets behind them.</p><h3>Basic Promise With A Single Then Method</h3><p>This is probably the simplest form of Promise you will ever come across and is the key to understanding how Promises really work. We have a simple promise constructor and when the promise is resolved it executes the resolved-callback/handler in the <strong>then method</strong>. The resolved handler is not called until the promise is resolved, in other words, it waits for the promises to be resolved. <strong><em>This is the key to the asynchronous nature of the Promises.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGJgbtebE2DVoPpxZ5ROrg.png" /><figcaption>Basic Promises with a single then method</figcaption></figure><p>Once the resolve method of the Promise constructor is called the resolve handler picks up the resolved value as an argument and prints it. Interestingly the then method doesn’t always behave this way in a Promise. Let’s see more of thens in the next section.</p><h3>Promises With Multiple Then Methods</h3><p>Now that we have understood how Promises generally work, let’s look at how the then method works. As said above the then method accepts both resolve and reject handlers, but for the sake of simplicity, we are just going to use resolve handlers along with the then method.</p><h4>Then method following a Promise constructor</h4><p>Then methods following a Promise constructor or a Promise object doesn’t execute the resolve/reject handler until the Promise resolves/rejects. The then method attached to the Promise constructor is the first handler to get invoked on resolve/reject of the Promise. <em>(Refer to the image above)</em></p><h4>Then method following another ‘then’ returning a value/reference</h4><p>The then methods following other then methods have different behaviour for promises and generic methods. The seemingly-synchronous behaviour is when the previous then the method doesn’t return any promises. Looking at the example below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGhwj-lR_ZkygpVlWyq3Bg.png" /><figcaption>Then methods executing without return values</figcaption></figure><p>Once the promises are resolved the then methods linked to the promises start executing one after the other, here you can add any number of thens and it can go on forever. <strong><em>Literally forever</em></strong>. This is similar to a code inside a really long function, executing one after the other. Although this is asynchronous by-nature, this can be a bit confusing for beginners.</p><blockquote>Note: one interesting behaviour of this is that when you do not return anything from the <strong>previous then method, </strong>x is undefined.</blockquote><h4>Then method following another ‘then’ returning a Promise</h4><p>When a then method returns a promise in a sequence, the execution is suspended until this promise resolved/rejected. This is otherwise called as <strong>‘Promise Chaining’</strong>, let’s see about it in the next section.</p><h3>Promise Chaining</h3><p>This is the core of Promise usage and possibly something which you need to understand before you can understand concepts around Async/await and Redux-sagas. Let’s take a deep dive.</p><p>Let’s consider we have two promise blocks, <em>(a Promise block is a Promise constructor followed by its own then methods)</em>. And we want one block to execute after the other, what do we do? We make use of the asynchronous behaviour of the then method.</p><blockquote><strong>When a then method returns a promise, the subsequent executions of the then are suspended until this promise block is resolved.</strong></blockquote><p>Let’s look at a more detailed example to understand further. In the following image, you can see clearly see three promise blocks and let’s understand how they form a promise chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyjkBeusmhUsMUbWlaZJKA.png" /><figcaption>Chaining promises</figcaption></figure><h4>Explanation</h4><ol><li>The promise1 is built with a constructor, and will automatically move to a pending state until resolved or rejected. At the instance of creation, this promise is still pending, which will get resolved after one second.</li><li>Similarly, promise2 and promise3 will also be pending, which will get resolved after 2 and 3 seconds respectively. <em>(we will see the order of resolutions in coming sections, don’t worry about it now)</em></li><li>At the1st second, promise1 is resolved and the resolved value of ‘first’ appears in the resolve handler.</li><li>The resolve handler returns another promise called promise2. Now the subsequent the thens following would have to wait till promise 2 is resolved.</li><li>The promise2 executes all the attached then methods, before continuing to execute the promise1’s then methods. <strong><em>The value returned by promise2 block’s last then method appears in the next occurring then of the promise1 block.</em></strong></li><li>Now again the execution is suspended till promise3 is resolved before finishing the whole execution.</li></ol><p>At first, the example might be a bit harder to understand, give it a good 10 minute read to wrap your head around it. Let it sink in before you move on to the next section.</p><h3>Promise Pyramid or Nested Promises</h3><p>The promise chain grows linearly from the top-down, but only problem in this approach is that we do not have access to the variables between different then methods or between different promise blocks.</p><p>Although there are different ways of achieving this, to keep it simpler we can use something called as <strong>Nested Promises</strong>. These nested promises will have access to variables from its outer scope, and are otherwise called as promise-pyramids, which will grow to the right. If not done correctly, this promise pyramid can eventually lead to something called as <strong><em>Promise-Callback Hell</em></strong>.</p><p>Let’s look at the problems accessing variables in promise-chaining below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lerxoGdExDF17YZsT7fCKA.png" /><figcaption>Problem with promise chaining</figcaption></figure><p>To ensure that all the consecutive promise blocks have access to all the parental scope variables, we can nest promises. Let’s look a simple two level nesting of promises to understand it better,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CMFoAPSWT9rFJUc2Ty9Bg.png" /><figcaption>Nested promises</figcaption></figure><p>In the nested promises, you can see that promise2’s then method resolves and prints both the value from the outer scope and the inner scope.</p><blockquote>A very important point to keep in mind is that during nesting sometimes we forget to return the nested promises, which will lead to an anti-pattern where your resolves/rejects will not bubble up to the top. Always!! I say always return a promise when its chained or nested.</blockquote><p><em>( You can try rejecting the promise2 and verify whether catch method successfully catches the error or not, take it as a challenge - </em><strong><em>with and without a return statement before promise2</em></strong><em>)</em></p><p>Sometimes nesting promises become inevitable which will inevitably lead to the callback hell we talked about, hence to tackle this issue ES7 has come up with Async/await. Be sure to check it out when you have time.</p><h3>Order of Execution of Promise Blocks</h3><p>Once you have mastered the nesting and chaining of promises, its now time to understand how promise execution works. Many developers think that promises would <strong><em>always wait till they are called or made use of</em></strong>, but that’s just wrong understanding of promises. A promise would try to resolve/reject it self as soon as possible, if it can.</p><p>There are two important points to remember about the promise execution cycle in a normal promise block and in a chained/nested promise block.</p><ol><li><strong><em>A promise once created races towards resolve/reject. If its resolved/rejected it changes its state to resolved and executes the attached then/catch method.</em></strong></li><li><strong><em>In a promise chaining or nesting when you return a promise inside a then method, and if the returned promise is already resolved/rejected, it will immediately call the subsequent then/catch method, if not it will wait.</em></strong></li></ol><p>Let’s look at an example to understand better,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDoMTG8fQKp5SsKAHJ7TOA.png" /><figcaption>Order of execution of promise blocks</figcaption></figure><h4>Explanation</h4><ol><li>promise1, promise2 and promise3 are initialised and they are racing towards resolve/reject in time. Currently, it is zeroth second.</li><li>In the1st second, all three promises are pending.</li><li>In the 2nd second, promise2 has resolved.</li><li>In the 3rd second, promise1 has resolved and the then handler is executed. In the then handler a resolved promise2 is returned. (a resolved promise holds resolved value and has a resolved state)</li><li>Since promise2 is already resolved it immediately calls the next then method attached, without waiting.</li><li>In the 3rd second the promise 3 is still pending because it needs two more seconds to be resolved.</li><li>After 5th second all three promises are resolved.</li></ol><h3>Catching errors in Promises</h3><p>Catching an error is pretty straightforward in promises, a catch method at the end of a promise block should do the trick. It handles both, when an error is <strong>thrown</strong> and when its <strong>rejected</strong>.</p><p>But throwing errors has its limitations in asynchronous coding, when we throw an error inside an async block of code it will never be caught. <strong><em>Alternatively, rejecting and returning a promise properly should work seamlessly without any issues and its considered the best practice.</em></strong></p><p>Also, you can reject a promise in any of its attached then methods by simply returning a <strong><em>Promise.reject(customErrorValue);</em></strong></p><h3>Promise.all() vs Promise.race()</h3><p><strong>Promise all</strong> resolves/rejects all the promises that are passed as an iterable before calling the then handler with an <strong><em>iterable result</em></strong>, whereas <strong>Promise race </strong>condition resolves/rejects the fastest promise that it can resolve/reject. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Read</a> more on the official docs.</p><h3><strong>Anti-patterns</strong></h3><p>There are many anti-patterns which you can avoid in a promise, but the main culprit is <strong>not returning promises and values</strong> properly. In a synchronous sequence of then methods following a Promise block, if a value is not returned from the previous then method it will not appear in the next occurring then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J61sri9eAgbiX33QFSAhnA.png" /><figcaption>Then methods with no-returns</figcaption></figure><p>Similarly, when we use a promise chaining, we need to return the promises. When we don’t return the promises, the consecutive then methods will not realise that it needs to wait for a promise in the sequence and simply assumes it as another line of code to be executed, there by losing its async nature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbb3XerNUICtHu-beKa8ww.png" /><figcaption>Promise chaining with/without return statement</figcaption></figure><blockquote><strong>Note:</strong> Only in the promise constructor block you do not have to explicitly return a resolve/reject. Apart from that, in the consecutive then methods, every value and promise chained needs to be returned, for accessing it further down the block.</blockquote><h3>Bonus Coding Challenge</h3><p>If you are interested in a Promise challenge, you can continue reading this para. Let’s assume that we have a for loop that prints 0 to 10 at random intervals (0 to 6 seconds). We need to modify it using promises to print sequentially 0 to 10. For example, if 0 takes 6 seconds to print and 1 takes two seconds to print, then 1 should wait for 0 to print and so on.</p><p>Hint: Use for loop to chain promises :).</p><p>Feel free to drop your solutions in the responses below.</p><h3>Conclusion</h3><p>Understanding Promises is the first step towards understanding Async/await and solving challenges faced in Promises using the ES7 alternatives. If you think that this was worth your time,<strong><em> leave some claps to show your support</em></strong>. And follow me on <a href="https://github.com/rajeshdavidbabu">GitHub</a>.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25ab752c78c3" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/playing-with-javascript-promises-a-comprehensive-approach-25ab752c78c3">Javascript Promises: An In-Depth API Guide</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[Deploy your Webpack apps to Heroku in 3 simple steps]]></title>
            <link>https://codeburst.io/deploy-your-webpack-apps-to-heroku-in-3-simple-steps-4ae072af93a8?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae072af93a8</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Mon, 28 May 2018 14:17:46 GMT</pubDate>
            <atom:updated>2022-08-04T13:20:22.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asyGC8WIGaqO6JvKbKXWeQ.png" /><figcaption>Webpack 4 with Heroku</figcaption></figure><p>If you are starting on web-development in 2018, I am sure all or at least most of your frontend projects are by default built and bundled using <strong>Webpack</strong>. Webpack has sunk into almost all the frontend projects we use nowadays and we have a really strong online dev community around Webpack to support us. If you are a beginner or even an intermediate to Webpack, I highly recommend this <a href="https://medium.freecodecamp.org/part-1-react-app-from-scratch-using-webpack-4-562b1d231e75">link</a> to get started on adding Webpack to your working web application.</p><p>This post is mainly aimed at people who are already using Webpack applications in their personal, GitHub or even client projects to successfully deploy and host their web applications on <strong>Heroku</strong>.</p><p>If you are new to <strong>Heroku</strong>, please check out the <a href="https://www.heroku.com/">link</a> to read further.</p><blockquote>In this post, I am going to quickly cover how to make an existing <strong>Webpack</strong> application deployment ready, (irrespective of the frontend libraries <strong>React </strong>or <strong>Vue</strong> <strong>JS</strong>) and help deploy your code on your <strong>Heroku</strong> account, in three simple steps. I have also attached my code repo at the end of the post, please feel free to clone/fork and play around with it.</blockquote><p><strong><em>Assuming that you already have a working Webpack application, let’s get into making it deployment ready for Heroku.</em></strong></p><h3><strong>1. Build an express server</strong></h3><p>The first step is to build a simple express server to serve your application. <em>What is an Express server you ask?</em></p><blockquote>An Express is a web-application framework that basically runs on a node environment. In our case it serves our application from a port available in the same environment.</blockquote><p>This is all you need to know to get started with building an express server. Unlike full-fledged express web applications, we are not going to serve each page based on an express router (<em>it’s not really important to know what I am talking about tbh..! </em>). Instead, we are going to build a simple standard express server to serve our index.html file.</p><p>This code might seem repetitive across many other blogs because it pretty much is the standard for building a simple express web server. Create a server.js and copy- paste this code.</p><pre><br>const express = require(&#39;express&#39;);<br>const path = require(&#39;path&#39;);<br>const port = process.env.PORT || 8080;<br>const app = express(); </pre><pre>// the __dirname is the current directory from where the script is // running<br>app.use(express.static(__dirname)); </pre><pre>// send the user to index html page inspite of the url<br>app.get(&#39;*&#39;, (req, res) =&gt; {<br>  res.sendFile(path.resolve(__dirname, &#39;index.html&#39;));<br>}); </pre><pre>app.listen(port);</pre><h4>Explanation</h4><ol><li><strong><em>__dirname</em></strong> points to the current directory from where the <strong><em>server.js</em></strong> is being run from and that is treated as the root of your project.</li><li>When we tell the express app to use a directory it automatically picks up the index.html file to serve.</li><li>We have also added an extra check to redirect the users back to index.html to avoid ‘not found’ errors and for the sake of simplicity.</li></ol><h3>2. Webpack Production Build</h3><p>This is a crucial step for us and it ensures that our application properly spits out a bundled js which we can use for deployment.</p><p>In the <strong>Webpack-cli</strong>, this is a simple one-liner, and it should spit out the output based on <strong><em>webpack.config.js</em></strong> we have.</p><pre>webpack -p </pre><p>In your <strong>webpack.config.js</strong> file, if you have the following code, you will see a <strong><em>bundle.js</em></strong> generated at the root of your application.</p><pre>module.exports = {<br>  entry: [<br>    &#39;./src/index.js&#39;<br>  ],<br>  output: {<br>    path: __dirname,<br>    publicPath: &#39;/&#39;,<br>    filename: &#39;bundle.js&#39;<br>  }<br>}</pre><p>On the flip-side when you do not have this config setup, your output will be generated in a <strong><em>/dist</em></strong> folder under the name <strong><em>main.js</em></strong>.</p><p>In both the cases, we need an HTML file and the location of your index.html determines where your express application should point to. Let’s say if you generate your<strong><em> index.html</em></strong> inside your <strong><em>/dist</em></strong> folder using a <strong><em>[htmlWebpackPlugin]</em></strong>, then the code that points to express <strong><em>app.use</em></strong> should be modified in the following way</p><pre>app.use(express.static(__dirname + &#39;/dist&#39;));</pre><p>In my case I do not use a <strong><em>[htmlWebpackPlugin]</em></strong>, instead I have a predefined <strong><em>index.html</em></strong> at the root of the folder where <strong><em>bundle.js </em></strong>is<strong><em> </em></strong>linked through the script tag.</p><blockquote><strong>Note</strong>: At this stage if you are not clear on what I am talking about, please download the code repo at the end of this post and check out the <strong>webpack.config.js</strong> file.</blockquote><h3><strong>3. Verify and deploy</strong></h3><p>If you have successfully generated the bundled js file either in the <strong><em>/dist</em></strong> folder or in your custom location and made sure that your generated/pre-defined <strong><em>index.html</em></strong> has a script tag pointing to the bundled js<strong><em>(main.js / bundle.js), you are now ready to ready to deploy your application.</em></strong></p><p>But before we jump the guns and deploy we need to make sure that the express server properly serves the application to <strong>localhost:8080.</strong></p><p>Run the following command in your terminal and verify if your application is being served on port 8080.</p><pre>node server.js</pre><p>Yes? Great, you are just two scripts away from deployment. No? verify your <strong>s<em>erver.js</em></strong> and make sure that you are pointing to the right directory and also check your <strong><em>webpack.config.js</em></strong> to see where your bundled js is being generated.</p><p>Now that we are here finally, close to deployment, we need to add two lines of script in our <strong><em>package.json</em></strong> file. Add these two following commands under the scripts section.</p><pre>&quot;scripts&quot;: {<br>  <strong>&quot;start&quot;: &quot;node server.js&quot;</strong>, // serves the application<br>  <strong>&quot;heroku-postbuild&quot;: &quot;webpack -p&quot;</strong> // runs after installation<br>},</pre><p><strong><em>Note</em>: </strong>Please replace the existing <strong>“start”</strong> command with <strong>“dev” </strong>and continue running dev server using <strong>npm run dev</strong> instead of <strong>start</strong>.</p><h4>Explanation</h4><blockquote><strong>Heroku</strong> automatically installs all our dependencies and goes on to do a<strong> post-build</strong> operation before serving our application. In this post-build operation, we do the production bundling of our js files and allow Heroku to kick-start the application by running the <strong>start</strong> command.</blockquote><p>Once you are done with the above, now let’s look at the deploying it to Heroku. Assuming that you already have a Heroku login and an account. Install the Heroku-cli following the instructions on this <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">link</a>.</p><p><em>Once you have installed the Heroku-CLI, follow the instructions below to deploy from the command line one after another.</em></p><pre><strong>heroku login </strong></pre><pre><strong>heroku create </strong></pre><pre><strong>git init </strong></pre><pre><strong>heroku git:remote --app &lt;your-heroku-app-name&gt;</strong></pre><pre><strong>git add . &amp;&amp; git commit -m &quot;initial commit&quot;</strong></pre><pre><strong>git push heroku master</strong></pre><h4>Explanation</h4><ol><li>Heroku login prompts you to enter username and password.</li><li>Heroku create command creates an application and gives you back the application URL and Heroku’s git repo for your project.</li><li>Re-initialize your project by running git init.</li><li>Add Heroku’s git repo as the remote repo of your current application.</li><li>Git add and commit .</li><li>Push to Heroku’s git repository.</li></ol><p>Visit your application URL generated at step 2, during Heroku create, you should be able to view your application. Voila !! your app is deployed :)</p><h3>Conclusion</h3><p>This should work for all the <strong>Webpack</strong> applications, irrespective of their frontend library, based on your web pack config file. The key thing to note here is your <strong><em>package.json</em></strong> file, make sure all the dependencies and dev-dependancies are part of it including <strong>Webpack</strong>.</p><p>I have created a <strong><em>Webpack 4 boilerplate with react and express server </em></strong>on my Github, please feel free to fork the code and try to run all the commands I have mentioned above.</p><p><strong>GitHub Repo </strong><a href="https://github.com/rajeshdavidbabu/react-for-heroku">Webpack-react-express Boilerplate</a></p><p>If you liked it please leave some claps to show your support. Also leave your responses below and reach out to me if you face any issues.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae072af93a8" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/deploy-your-webpack-apps-to-heroku-in-3-simple-steps-4ae072af93a8">Deploy your Webpack apps to Heroku in 3 simple steps</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[A Simple Guide to Understanding Javascript (ES6) Generators]]></title>
            <link>https://medium.com/dailyjs/a-simple-guide-to-understanding-javascript-es6-generators-d1c350551950?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1c350551950</guid>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[es6-in-depth]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Fri, 04 May 2018 22:35:00 GMT</pubDate>
            <atom:updated>2023-03-29T13:33:28.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4877k4Hq9dPdtmvg9hnGFA.jpeg" /></figure><p>If you’ve been a JavaScript developer for the last two to five years you will have definitely come across posts talking about <strong>Generators</strong> and <strong>Iterators</strong>. While <strong>Generators</strong> and <strong>Iterators </strong>are inherently associated, Generators seem a bit more intimidating than the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwQSEHpbaNHte95IW2kTCw.jpeg" /><figcaption>Generator Turbine</figcaption></figure><blockquote><strong>Iterators </strong>are an implementation of <strong>Iterable</strong> objects such as maps, arrays and strings which enables us to iterate over them using next(). They have a wide variety of use cases across Generators, Observables and Spread operators.</blockquote><blockquote>I recommend the following link for those of you who are new to iterators, <a href="https://codeburst.io/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e">Guide to Iterators</a>.</blockquote><p>To check if your object conforms to the iterable protocol, verify using the built-in Symbol.iterator:</p><pre><strong>new Map([[1, 2]])[Symbol.iterator]()</strong> // MapIterator {1 =&gt; 2}<br><strong>“hi”[Symbol.iterator]()</strong> // StringIterator {}<br><strong>[‘1’][Symbol.iterator]()</strong> // Array Iterator {}<br><strong>new Set([1, 2])[Symbol.iterator]()</strong> // SetIterator {1, 2}</pre><p><strong>Generators</strong> introduced as part of ES6 have not undergone any changes for the further JavaScript releases and they are here to stay longer. I mean really long! So there is not running away from it. Although ES7 and ES8 have some new updates, they do not have the same magnitude of change that ES6 had from ES5, which took JavaScript to the next level, so to speak.</p><p><strong>By the end of this post, I am positive that you will have a solid understanding of how function Generators work</strong>. If you are a pro, please help me improve the content by adding your comments in the responses. Just in case if you have difficulty following the code, I have also added explanation for most of the code to help you understand better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><h3>Introduction</h3><p>Functions in JavaScript, as we all know, <strong><em>“run until return/end”. Generator Functions </em></strong>on the other hand, <strong><em>“run until yield/return/end”. </em></strong>Unlike the normal functions <strong>Generator Functions</strong> once called, returns the <strong>Generator Object, </strong>which holds the entire <strong>Generator Iterable</strong> that can be iterated using <strong>next()</strong> method or <strong>for…of </strong>loop.</p><blockquote>Every next() call on the generator executes every line of code until the next yield it encounters and suspends its execution temporarily.</blockquote><p>Syntactically they are identified with a <strong>*</strong>, either <strong>function* X </strong>or <strong>function *X</strong>,<strong> </strong>— both mean the same thing.</p><p>Once created, calling the generator function returns the <strong>Generator Object. </strong>This generator object needs to be assigned to a <strong>variable</strong> to keep track of the subsequent <strong>next()</strong> methods called on itself. <strong><em>If the generator is not assigned to a variable then it will always yield only till first yield expression on every next().</em></strong></p><p>The generator functions are normally built using <strong><em>yield expressions</em></strong>. Each <strong><em>yield</em></strong> inside the generator function is a stopping point before the next execution cycle starts. Each execution cycle is triggered by means of <strong><em>next() </em></strong>method on the generator.</p><p>On each <strong><em>next()</em></strong> call, the <strong><em>yield</em></strong> expression returns its value in the form of an object containing the following parameters.</p><p>{ value: 10, done: false } // assuming that 10 is the value of yield</p><ul><li><strong>Value</strong> — is everything that is written on the right side of the <strong><em>yield</em></strong> keyword, it can be a function call, object or practically anything. For empty yields this value is <strong><em>undefined</em></strong>.</li><li><strong>Done</strong> — indicates the status of the generator, whether it can be executed further or not. When done returns true, it means that the function has finished its run.</li></ul><p><em>(If you feel that its a bit over your head, you will get more clarity once you see the example below…)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnOJNuFe-r9T7pO47mVYaw.png" /><figcaption>Basic generator function</figcaption></figure><blockquote><strong>Note:</strong> In the above example the <strong>generator function</strong> accessed directly without a wrapper always executes only until the first yield. Hence, by definition you need to assign the Generator to a variable to properly iterate over it.</blockquote><h3>Lifecycle of a Generator Function</h3><p>Before we proceed further, let’s take a quick look at the block diagram of the Generator Function’s life-cycle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pLkX6yrbV2r6_pZ10AIvQ.png" /><figcaption>Life-cycle of a Generator Function</figcaption></figure><p>Each time a <strong><em>yield</em></strong> is encountered the generator function returns an object containing the <strong><em>value</em></strong> of the encountered yield and the <strong><em>done</em></strong> status. Similarly, when a <strong><em>return</em></strong> is encountered, we get the return value and also <strong><em>done</em></strong> status as <strong><em>true</em></strong>. Whenever, done status is returned as true, is essentially means that the <strong><em>generator function</em></strong> has completed its run, and no further yield is possible.</p><blockquote>Everything after the first <strong>return</strong> is ignored, including other <strong>yield</strong> expressions.</blockquote><p><em>Read further to understand the block diagram better.</em></p><h3>Assigning Yield to a Variable</h3><p>In the previous code sample we saw an introduction to creating a basic generator with a yield. And got the expected output. Now, let’s assume that we assign the entire yield expression to a variable in the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdJQlUaqIiD3eV0j0QzrZA.png" /><figcaption>Assigning yield to a variable</figcaption></figure><blockquote>What is the result of the entire yield expression passed to the variable ? <strong><em>Nothing or Undefined …</em></strong></blockquote><blockquote>Why ? <strong><em>Starting from second next(), the previous yield is replaced with arguments passed in the next function. Since, we do not pass anything here in the next method, its assumed that the entire ‘previous-yield expression’ as undefined.</em></strong></blockquote><p>With this in mind, let’s jump to the next section to understand more about passing argument to the next() method.</p><h3>Passing Arguments to the next() Method</h3><p>With reference to the block diagram above, let’s talk about passing arguments into the next function. <strong><em>This is one of the most trickiest part of the whole generator implementation</em></strong>.</p><p>Let’s consider the following piece of code, where the yield is assigned to a variable, but this time we pass a value in the next() method.</p><p>Let’s look at the code below in the console. And the explanation right after that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYCKrAkgSyfEeN9cswZzbA.png" /><figcaption>Passing arguments to the next()</figcaption></figure><h4>Explanation:</h4><ol><li>When we call the<strong><em> first next(20)</em></strong>, every line of code till the first yield is printed. As we do not have any previous yield expression this value 20 is discarded. In the output we get yield value as i*10, which is 100 here. Also the state of the execution stops with first yield and the <strong><em>const j</em></strong> is not yet set.</li><li>The second <strong><em>next(10)</em></strong> call, replaces the entire first yield expression with 10, imagine <strong><em>yield (i * 10) = 10, </em></strong>which goes on to set the value of <strong><em>const j to 50 </em></strong>before returning the second yield’s value. The yield value here is <strong><em>2 * 50 / 4 = 25</em></strong>.</li><li>Third <strong><em>next(5)</em></strong>, replaces the entire second yield with 5, bringing the value of k to 5. And further continues to execute return statement and return <strong><em>(x + y + z) =&gt; (10 + 50 + 5) = 65</em></strong> as the final yield value along with done true.</li></ol><blockquote><strong>This might be bit overwhelming for the first time readers, but take a good 5 minutes to read it over and over again to understand completely.</strong></blockquote><h3>Passing Yield as an Argument of a Function</h3><p>There are n-number of use-cases surrounding yield regarding how it can be used inside a function generator. Let’s look at the code below for one such interesting usage of yield, along with the explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6pwTwJ7stPZzAeCKBfv4Q.png" /><figcaption>Yield as an argument of a function</figcaption></figure><h4>Explanation</h4><ol><li>The first next() yields undefined value because yield expression has no value.</li><li>The second next() yields “I am usless”, the value which was passed. And prepares argument for function call.</li><li>The third next(), calls the function with an <strong><em>undefined</em></strong> argument. As mentioned above, the next() method called without any arguments essentially means that the <strong><em>entire previous yield expression is undefined</em></strong>. Hence, this prints <strong><em>undefined </em></strong>and finishes the run.</li></ol><h3>Yield with a Function Call</h3><p>Apart from returning values yield can also call functions and return the value or print the same. Let’s look at the code below and understand better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXpsq-hlqla3z3mZGWyTJw.png" /><figcaption>Yield calling a function</figcaption></figure><p>The code above returns the function’s return obj as the yield value. And ends the run by setting <strong><em>undefined</em></strong> to the <strong><em>const user</em></strong>.</p><h3>Yield with Promises</h3><p>Yield with promises follows the same approach as the function call above, instead of returning a value from the function, it returns a promise which can be evaluated further for success or failure. Let’s look at the code below to understand how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*100c_wLxJHmcKtjZAYwJzw.png" /><figcaption>Yield with promises</figcaption></figure><p>The apiCall returns the promises as the yield value, when resolved after 2 seconds prints the value we need.</p><h3>Yield*</h3><p>So far we have been looking at the use cases for yield expression, now we are going to look at another expression called <strong><em>yield*</em></strong><em>.</em><strong><em> Yield*</em></strong> when used inside a generator function<strong><em> </em></strong>delegates another generator function. Simply put, it synchronously completes the generator function in its expression before moving on to the next line.</p><p>Let’s look at the code and the explanation below to understand better. This code is from the MDN web docs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMlOmBoi2XGCE3qwUIj3qA.png" /><figcaption>Basic yield*</figcaption></figure><h4>Explanation</h4><ol><li>The first next() call yields a value of 1.</li><li>The second next() call, however, is a <strong><em>yield* expression</em></strong>, which inherently means that we are going to complete another generator function specified in the <strong><em>yield* expression</em></strong> before continuing the current generator function.</li><li>In your mind, you can assume that the code above is replaced like the one below</li></ol><pre>function* g2() {<br>  yield 1;<br>  yield 2;<br>  yield 3;<br>  yield 4;<br>  yield 5;<br>}</pre><blockquote>This will go on to finish the generator run. However, there is one distinct ability of the <strong><em>yield*</em></strong> which you should keep in mind while using <strong><em>return</em></strong>, in the next section.</blockquote><h3>Yield* with Return</h3><p>Yield* with a return behaves a bit differently than the normal yield*. When yield* is used with a return statement it evaluates to that value, meaning the entire yield* function() becomes equal to the value returned from the associated generator function.</p><p>Let’s look at the code and the explanation below to understand it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxJtIuXhBnOMAK0cwVElsQ.png" /><figcaption>Yield* with return</figcaption></figure><h4><strong>Explanation</strong></h4><ol><li>In the first next() we go straight to the yield 1 and return its value.</li><li>The second next() yields 2.</li><li>The third next(), <strong><em>returns ‘foo’</em></strong> and goes on to yield the ‘the end’, assigning ‘foo’ to the <strong><em>const result</em></strong> on the way.</li><li>The last next() finishes the run.</li></ol><h3><strong>Yield* with a Built-in Iterable Object</strong></h3><p>There is one more interesting yield* property worth-mentioning, similar to the return value, <strong><em>yield*</em></strong> can also iterate over iterable objects like Array, String and Map.</p><p>Let’s look at how it works in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*u6RQVCQBCqw5UsF3Kger1w.png" /><figcaption>Yield over built-in iterables</figcaption></figure><p>Here in the code the yield* iterates over every possible iterable object that is passed as its expression. I guess the code itself is self-explanatory.</p><h3>Best Practices</h3><p>On top of all this, every iterator/generator can be iterated over a <strong>for…of </strong>loop. Similar to our next() method which is called explicitly, for…of loop internally moves on to the next iteration based on the <strong><em>yield keyword</em></strong>. And it iterates only till the <strong><em>last yield</em></strong> and doesn’t process the return statements like the next() method.</p><p>You can verify the same in the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*dDYt_xElLC7wjUDN7HfDJg.png" /><figcaption>Yield with for…of</figcaption></figure><blockquote>The final return value is not printed, because for…of loop iterates only till the last yield. So, it comes under best practice to avoid return statements inside a generator function as it would affect the reusability of the function when iterated over a <strong>for…of</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4877k4Hq9dPdtmvg9hnGFA.jpeg" /></figure><h3>Conclusion</h3><p>I hope this covers the basic use-cases of generator functions and I sincerely hope that it gave a better understanding of how generators work in JavaScript ES6 and above. If you like my content please leave <strong><em>1, 2, 3 or even 50 claps :)</em></strong>.</p><p>Please follow me on my GitHub account for more JavaScript and Full-Stack projects:</p><p><a href="https://github.com/rajeshbabu-oviva">https://github.com/rajeshbabu-oviva</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c350551950" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dailyjs/a-simple-guide-to-understanding-javascript-es6-generators-d1c350551950">A Simple Guide to Understanding Javascript (ES6) Generators</a> was originally published in <a href="https://medium.com/dailyjs">DailyJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array vs Set vs Map vs Object — Real-time use cases in Javascript (ES6/ES7)]]></title>
            <link>https://codeburst.io/array-vs-set-vs-map-vs-object-real-time-use-cases-in-javascript-es6-47ee3295329b?source=rss-17f85189cad1------2</link>
            <guid isPermaLink="false">https://medium.com/p/47ee3295329b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[es7]]></category>
            <dc:creator><![CDATA[Rajesh Babu]]></dc:creator>
            <pubDate>Sun, 29 Apr 2018 21:23:55 GMT</pubDate>
            <atom:updated>2023-03-28T20:37:25.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv0VzEqlCXAKAt_iZvDzcA.jpeg" /><figcaption>Ocean Fishing</figcaption></figure><p>The internet is a great place to find information, but there is one teeny-tiny problem. You are on a boat in the middle of a deep blue sea. Although most of us do not venture all the way down into the darkness, we still precisely like to get what we want. (Oh! The Internet is the deep blue sea I was talking about).</p><p><em>As frontend developers most of the times we do not rely on vanilla javascript for everything that we want. Most of the times we pledge our allegiance to our lords (frameworks) and libraries and follow them blindly because we think that they are capable of doing everything, sometimes losing out on javascript best practices.</em></p><p>Recently, I got the chance to work on a backbone application where <strong><em>I understood the primary importance of selectively using javascript built-in objects for our operations regardless of the framework</em></strong>. And figured that I could write down my thoughts on the reasoning to choose a specific data-structure based on the type of operation that is required.</p><h3>1. Search/Find</h3><p>Let’s look at how we can find a particular element in all the four built-in javascript objects for different use-cases.</p><h4>Array</h4><pre>// array of objects<br><strong>array.find(object =&gt; object.id === 2);</strong> // returns object with id 2</pre><pre>//array of numbers starting from &quot;zero&quot;<br><strong>array.indexOf(&quot;one&quot;);</strong> // returns 1 as index</pre><h4>Object</h4><pre>// array of Objects<br>// eg: [{id: 1, name: &quot;one&quot;},...] can be converted to {1: {name: &quot;one&quot;}, ... }<br><strong>object[2]</strong> // returns the value of key 2 (i.e {name: &quot;two&quot;} </pre><blockquote>Note: When using n-operations to find an object, its always best to use object key for retrieving the item rather than array find.</blockquote><h4>Set</h4><p>Sets have no built-in function to retrieve or find the index of its items even-though its an iterable, so ideally we would have to convert it to an array before indexOf/find operation.</p><pre><strong>const mySet = new Set([&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]);</strong><br><strong>[...mySet].indexOf(&#39;2&#39;)</strong> // returns 1</pre><pre><strong>const mySet = new Set([{1: &#39;one&#39;}, {2: &#39;two&#39;}, {3: &#39;three&#39;}]);</strong><br><strong>[...mySet].find(object =&gt; object[2] === &#39;two&#39;);</strong> // returns {2: &#39;two&#39;}</pre><h4>Map</h4><p>Maps are special objects per se, they are iterables with key value pair constructor that looks like a 2D array but acts like an object. They offer a better flexibility in terms of choosing our key values. A map can have a key value which can be a string, number, object or even NaN.</p><pre><strong>var map = new Map([[ 1, &#39;one&#39; ],[ 2, &#39;two&#39; ]]);<br>map.get(1) </strong>// returns &#39;one&#39;</pre><blockquote><strong>Note:</strong> Maps can be very flexible in places where objects can be a bit annoying, and it strongly serves the purpose in some specific scenarios, like adding and deleting key-pairs frequently.</blockquote><h3>2. Sort</h3><p>Sort operations can be interesting, and most of the times we assume that sort over an iterable entity works out of the box. Well, it doesn’t always.</p><h4>Array</h4><p>Array sorts are often misunderstood by both beginners and intermediate developers. Since array’s default sort sorts an array based on Unicode , we cannot expect to get same sort behaviour for all the datatypes. Hence, we often need to pass a comparator function into the sort.</p><pre>// array of strings in a uniform case without special characters<br><strong>const arr = [ &quot;sex&quot;, &quot;age&quot;, &quot;job&quot;];<br>arr.sort();</strong> //returns [&quot;age&quot;, &quot;job&quot;, &quot;sex&quot;]</pre><pre>// array of numbers<br><strong>const arr = [ 30, 4, 29 , 19];<br>arr.sort((a, b) =&gt; a-b);</strong> // returns [4, 19, 29, 30]</pre><pre>// array of number strings<br><strong>const arr = </strong>[ &quot;30&quot;, &quot;4&quot;, &quot;29&quot; , &quot;19&quot; ];<br><strong>arr.sort((a, b) =&gt; a-b);</strong> // returns [&quot;4&quot;, &quot;19&quot;, &quot;29&quot;, &quot;30&quot;]</pre><pre>// array of mixed numerics<br><strong>const arr = [ 30, &quot;4&quot;, 29 , &quot;19&quot; ];</strong><br><strong>arr.sort((a, b) =&gt; a-b);</strong> // returns [&quot;4&quot;, &quot;19&quot;, 29, 30]</pre><pre>// array of non-ASCII strings and also strings<br><strong>const arr = [&#39;réservé&#39;, &#39;cliché&#39;, &#39;adieu&#39;];<br>arr.sort((a, b) =&gt; a.localeCompare(b));</strong> // returns is [&#39;adieu&#39;, &#39;cliché&#39;,&#39;réservé&#39;]</pre><pre>// array of objects<br><strong>const arr = [<br>  { name: &#39;Sharpe&#39;, value: 37 },<br>  { name: &#39;And&#39;, value: 45 },<br>  { name: &#39;The&#39;, value: -12 }<br>];</strong><br>// sort by name string<br><strong>arr.sort((a,b) =&gt; a[&#39;name&#39;].localeCompare(b[&#39;name&#39;]));</strong></pre><pre>// sort by value number<br><strong>arr.sort((a,b) =&gt; a[&#39;value&#39;]-b[&#39;value&#39;]);</strong></pre><blockquote><strong>Note:</strong> I usually prefer using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare">localeCompare</a> to sort my strings as they offer more flexibility of controlling case-sensitivity, accent and also give us the benefit of considering language during the sort.</blockquote><h4>Object</h4><p>There is no built-in method for the sorting of the objects, but ES6 offers some interesting built-in key-sorting during the creation of the object. Object keys are sorted only based on numerics/numeric-strings, all the other keys are pushed right after the numeric keys unsorted.</p><pre>// object with numeric/numeric-string keys are sorted<br><strong>const obj = { 30: &#39;dad&#39;, &#39;4&#39;: &#39;kid&#39;, 19: &#39;teen&#39;, &#39;100&#39;: &#39;grams&#39;};<br>console.log(obj)</strong> // returns {4: &quot;kid&quot;, 19: &quot;teen&quot;, 30: &quot;dad&quot;, 100: &quot;grams&quot;} with sorted keys</pre><pre>// object with key-values as alpha-strings are not sorted<br><strong>const obj = { &quot;b&quot;: &quot;two&quot;, &quot;a&quot;: &quot;one&quot;, &quot;c&quot;: &quot;three&quot; };</strong><br><strong>console.log(obj) </strong>// returns {b: &quot;two&quot;, a: &quot;one&quot;, c: &quot;three&quot;}</pre><pre>// object with numeric, numeric-string and alpha keys are partially sorted. (i.e only numeric keys are sorted)<br><strong>const obj = { b: &quot;one&quot;, 4: &quot;kid&quot;, &quot;30&quot;: &quot;dad&quot;, 9: &quot;son&quot;, a: &quot;two&quot; };<br>console.log(obj)</strong> // returns {4: &quot;kid&quot;, 9: &quot;son&quot;, 30: &quot;dad&quot;, b: &quot;one&quot;, a: &quot;two&quot;}</pre><h4>Set</h4><p>Sets do not have built-in sort functionality, however the easiest way to sort a set is to convert it to an array and implementing array’s sort method. Since, set is an iterable object, we can build our own sorting algorithm of our choice.</p><pre>// set to array and array sort <strong><br>const set = new Set([&#39;b&#39;, &#39;a&#39;, &#39;c&#39;]);<br>[...set].sort();</strong> // returns [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;] which is an array</pre><pre>// alternatively we can use entries to sort a set and create a new sorted set. The iterator gives us the [&#39;a&#39;, &#39;a&#39;] when spread over an array.<br><strong>const set = new Set([&#39;b&#39;, &#39;a&#39;, &#39;c&#39;]);</strong><br><strong>const sortedSet = new Set([...set.entries()].map((entry) =&gt; entry[0]).sort());</strong></pre><blockquote><strong>Note:</strong> Keep in mind that sort method is of array’s and you would have to use a comparator appropriately to get your desired sort.</blockquote><h4>Map</h4><p>Similar to sets maps do not have a built-in method themselves, but we can still spread their entries over an array and build a new sorted map.</p><pre>// entries spread over an array can be sorted like an array<br><strong>const map = new Map([[&quot;c&quot;, &#39;three&#39;],[&quot;a&quot;, &#39;one&#39;], [&quot;b&quot;, &#39;two&#39;]]);<br>const sortedMap = new Map([...map.entries()].sort()) </strong>// returns sorted Map(3) {&quot;a&quot; =&gt; &quot;one&quot;, &quot;b&quot; =&gt; &quot;three&quot;, &quot;c&quot; =&gt; &quot;two&quot;}</pre><blockquote><strong>Note:</strong> In the map sorting, it is important to know that the two-dimensional array from the map gets sorted based on the first element in each sub-array. Here the sorting is based on “a”, “b” and “c” strings. If these were numbers, you would have to use a comparator.</blockquote><h3>3. Includes or Has</h3><p>One of the most important features of the iterable objects is to check the presence of the desired item. Almost, all of the built-in standard and iterable javascript objects have their own implementation to achieve this. Let’s look at them below.</p><h4>Array</h4><pre>// we are considering a linear array only<br><strong>const arr = [1, 2, 3];</strong><br><strong>arr.includes(1);</strong> // returns true<br><strong>arr.includes(&#39;1&#39;);</strong> // returns false as types do not match</pre><h4><strong>Object</strong></h4><pre>// we are going to consider only the keys<br><strong>const obj = { a: 1, b: 2, c: 3, 1: &#39;one&#39; };</strong><br><strong>obj.hasOwnProperty(&#39;a&#39;);</strong> // returns true<br><strong>obj.hasOwnProperty(&#39;1&#39;);</strong> // returns true because no type check<br><strong>obj.hasOwnProperty(1);</strong> // returns true</pre><h4>Set</h4><p>Set has a handy ‘has’ function which can be more efficient in accessing the values compared to an array.</p><pre><strong>const set = new Set([1, 2, 3, 4, 5]);</strong><br><strong>set.has(4);</strong> // returns true<br><strong>set.has(&#39;4&#39;);</strong> // returns false because of mismatch in type</pre><h4>Map</h4><p>Map has a built-in ‘has’ function too.</p><pre><strong>const map = new Map([[3, &#39;three&#39;],[&quot;a&quot;, &#39;one&#39;], [&quot;b&quot;, &#39;two&#39;]]);<br>map.has(&#39;a&#39;);</strong> // returns true<br><strong>map.has(3);</strong> // returns true<br><strong>map.has(&#39;3&#39;);</strong> // returns false because types don&#39;t match</pre><blockquote><strong>Note:</strong> Compared to the array’s <strong>includes</strong> function, Object’s <strong>hasOwnProperty </strong>and Set/Map’s <strong>has</strong> functions seem to perform close to O(1) in different tests, clearly more efficient in terms of larger data sets.</blockquote><h3>4. Removing Duplicates</h3><p>There is no straight forward way to remove duplicates in a collection, given that array or object is linear, we can use some of the built-in methods to remove duplicates.</p><h4>Array</h4><p>There are many online methods to remove duplicates from an array. That this s<a href="https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array">tackoverflow</a> thread covers. However in ES6 let’s look at the easiest ways of removing duplicates from an array.</p><pre>// considering a linear array Set gives us the answer we need.<br><strong>const arr = [1, 2, 2, 4, 5, 5];<br>[...new Set(arr)]; </strong>// returns [1, 2, 4, 5]</pre><pre>// however set doesn&#39;t remove duplicates from array of objects<br><strong>const arr = [{a:1},{b:2},{a:1}];<br>[...new Set(arr)]; </strong>// returns [{a:1},{b:2},{a:1}]</pre><pre>// hence we can use ES6 filter and map functions to achieve the same<br><strong>arr.filter((obj, index) =&gt; { <br>  return arr.map(obj =&gt; obj[&#39;a&#39;]).indexOf(obj[&#39;a&#39;]) === index;    <br>});</strong> // removes duplicate based on the key &#39;a&#39;</pre><blockquote><strong>Note:</strong> Set will remove the duplicate objects if they are stringified and the strings match, but we still have to parse then back to the object once set is converted back to an array. The whole process might not be performant.</blockquote><h4>Object</h4><p>Objects do not allow duplicate key values, old values are overwritten by the new values.</p><pre><strong>const obj = { b: &quot;one&quot;, a: &quot;two&quot;, a: &quot;three&quot; };</strong><br><strong>console.log(obj);</strong> // returns {b: &quot;one&quot;, a: &quot;three&quot;}</pre><h4><strong>Set</strong></h4><p>Sets inherently do not allow duplicate values when they are passed a linear iterable object like an array, but when they are passed an array of object they do allow duplicate objects.</p><pre>// a linear array iterable<strong><br>const set = new Set([1, 2, 2, 4, 5, 5]);<br>console.log(set); </strong>// returns Set {1, 2, 4, 5}</pre><pre>// array of objects<br><strong>const set = new Set([{a:1},{b:2},{a:1}]);<br>console.log(set); </strong>// returns Set {{a:1},{b:2},{a:1}} with duplicate objects</pre><h4>Map</h4><p>Maps also do not allow duplicate keys during the creation.</p><pre><strong>const map = new Map([[3, &#39;three&#39;], [2, &#39;two&#39;], [2, &#39;four&#39;]]);<br>console.log(map);</strong> // returns {3 =&gt; &quot;three&quot;, 2 =&gt; &quot;four&quot;} </pre><h3>5. Delete</h3><h4>Array</h4><p>Array has no built-in method to delete its items. However we can use couple of methods to do it. Splice, indexOf or filter.</p><pre><em>// I personally prefer this method.</em><br><strong>const arr = [ &#39;a&#39;, &#39;b&#39;, &#39;c&#39; ];<br>arr.filter(e =&gt; e !== &#39;c&#39;);</strong> // returns [ &#39;a&#39;, &#39;b&#39; ] removing &#39;c&#39;</pre><h4><strong>Object</strong></h4><p>Objects do not have a built-in delete method, but according to the docs we can use the delete keyword to delete a key. However, this is widely discouraged in the javascript community and even libraries like underscore and lodash use a different method.</p><pre>// The infamous delete method<strong><br>const obj = { b: &quot;one&quot;, a: &quot;two&quot; };<br>delete obj.a; </strong>// deletes a and returns true</pre><h4>Set</h4><p>Set offers a built-in delete method making our lives easier</p><pre><strong>const set = new Set([1, 2, 4, 5]);<br>set.delete(4); </strong>// deletes 4 and returns true<strong><br>set.delete(&#39;5&#39;); </strong>// returns false as types do not match</pre><h4>Map</h4><p>Map has its own built-in delete method to remove keys from a given map object.</p><pre><strong>const map = new Map([[3, &#39;three&#39;], [2, &#39;two&#39;]);<br>map.delete(3);</strong> // deletes [3, &#39;three&#39;] and returns true.<br><strong>map.delete(&#39;2&#39;);</strong> // returns false as types do not match</pre><h3>6. Length and Size</h3><pre>// arrays have a built-in property for length which is different from collection size.<br><strong>[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;].length </strong>// returns 3</pre><pre>// objects have no built-in property to check length or size, so we need to resort to using keys array to check length.<br><strong>Object.keys({ b: &#39;one&#39;, a: &#39;two&#39;, c: &#39;three&#39; }).length </strong>// returns 3</pre><pre>// set has a size property built-in<br><strong>new Set([{a:1},{b:2},{a:1}]).size</strong> // returns 3</pre><pre>// map has a size property built-in<br><strong>new Map([[3, &#39;three&#39;],[&#39;a&#39;, &#39;one&#39;], [&#39;b&#39;, &#39;two&#39;]])</strong>.<strong>size</strong> // returns 3</pre><h3>Conclusion</h3><p>These are some of the key pointers to remember when choosing the standard built-in objects of your choice. Though javascript offers us the flexibility of using more than one built-in objects, its always better to choose the one that suits the best. Feel free to leave your comments below.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47ee3295329b" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/array-vs-set-vs-map-vs-object-real-time-use-cases-in-javascript-es6-47ee3295329b">Array vs Set vs Map vs Object — Real-time use cases in Javascript (ES6/ES7)</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>