<?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 Shashank Vivek on Medium]]></title>
        <description><![CDATA[Stories by Shashank Vivek on Medium]]></description>
        <link>https://medium.com/@shashankvivek-7?source=rss-41c54a11f4df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*socXHzckxHciy7ynJQpTiw.jpeg</url>
            <title>Stories by Shashank Vivek on Medium</title>
            <link>https://medium.com/@shashankvivek-7?source=rss-41c54a11f4df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:03:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashankvivek-7/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[Add Batman in Your VS Code]]></title>
            <link>https://shashankvivek-7.medium.com/running-batman-in-your-vs-code-44e525957f14?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e525957f14</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 11:57:10 GMT</pubDate>
            <atom:updated>2021-09-08T17:22:04.692Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Software Developer, it is not always about writing code. We also share a passion to personalize our workstations and development environment. I have personally been a fan of that aspect. Very often, I customize fonts, icons and themes of my VS code.</p><p>In this short yet fun article, I’ll explain to you a plugin that I love and customize to make my IDE a fun place to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTPRDKSfqKKX-Dv_j77cRQ.png" /></figure><p>The extension name is “Power Mode” that you can find in the marketplace of VS Code extension. This is how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCawCOacoJecZFkZy6wKFw.png" /></figure><p>Once installed, you can see the fun part after enabling the feature from Settings of VS Code ( Files &gt; Preferences &gt; Settings).</p><p>Select a type of animation by searching for Power Mode and enable it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cPHfU1YHWhXao8dzOeCow.png" /></figure><p>And here is how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QjfLoK1KjJbTUNBze5GWEw.gif" /></figure><p>But our fun does not stop there. This can be easily done by anyone. So, let’s customize it further with my favorite Superhero <strong>Batman 😄.</strong></p><p>To add our custom animation, we should open settings.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZEXbJYetguqYLnEjnRsPA.png" /></figure><p>Clicking on either of these links work. Once opened, copy paste below code to the settings.json</p><pre>&quot;powermode.customExplosions&quot;: [<br>     &quot;<a href="https://c.tenor.com/xT0EW92-o60AAAAi/batman-dc.gif">https://c.tenor.com/xT0EW92-o60AAAAi/batman-dc.gif</a>&quot;<br>],<br>&quot;powermode.customCss&quot;: {    <br>   &quot;margin-top&quot;: &quot;1rem&quot;,<br>   &quot;height&quot;: &quot;5rem&quot;,<br>   &quot;width&quot;: &quot;5rem&quot;,<br>},</pre><p>The final json structure may look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lpe4vT3JgzkkNo9cbSn4Ow.png" /></figure><p>After saving the file, you should be able to see the <strong>Batman</strong> in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-p9-kQFQVtbwNhu97PqMKA.gif" /></figure><p>You can play around and find more stickers on <a href="https://tenor.com/">https://tenor.com/</a> .</p><p>If you find some fun stickers, feel free to drop its detail in the comment section of this article. 😉</p><p>Have Fun ! 🐼</p><blockquote>If you like this article, please 👏 clap 👏 few times &amp; encourage me 🐼 to write more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e525957f14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Smart Angular Spinner - Scoping on App as well as Component]]></title>
            <link>https://shashankvivek-7.medium.com/a-smart-angular-spinner-scoping-on-app-as-well-as-component-f9f8dd3e191c?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f8dd3e191c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 12:20:38 GMT</pubDate>
            <atom:updated>2021-04-21T01:21:57.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Smart Angular Spinner - Scoping on App as well as Component Level</h3><p>Creating spinner components in Angular is done in almost all web apps. The 1st rule of thumb is to avoid Spinners as much as we can. There are several smart ways to do that. I’ll keep that to a different article. In this article, we will be creating the same old spinner of Angular but with a little trick up its sleeve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ishwNQpdIGt2EzCB9ALJZg.png" /></figure><p>In my frontend development experience with different MNCs, I have seen spinner implementation in few different ways.</p><ol><li>Create a separate <strong>Spinner Component</strong> and add the selector wherever it has to be used in other components. Set *ngIf flag to show and hide the spinner inside the component.</li><li>Create a global Spinner Component and keep calling it via service. Generally, it is applied on app level and the entire UI is blocked while the data is loading.</li></ol><p>In one of my projects, I came across a spinner component that was applied on the app level. Anytime it was called using spinner service, the entire UI was blocked. It was a straightforward implementation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-nzeoxb%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fspinner%252Fspinner.html&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-nzeoxb%3Ffile%3Dsrc%252Fapp%252Fspinner%252Fspinner.html&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-03bbb9acbba813917725387f46e5df03a95d232be240e910ce5f946a973b3f86.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb4d5b6d8d4ebd08accdaf1e29ee7990/href">https://medium.com/media/bb4d5b6d8d4ebd08accdaf1e29ee7990/href</a></iframe><p>So far, so good. But later on, I realized that there were few screens that contained several small components to show data (<strong>for example: </strong>a Dashboard UI). Hence an app level spinner would restrict the user interaction time until the entire data of all components are loaded. This seems to be a problem to manage because unless the entire data is loaded, the dashboard UI will be blocked.</p><p>I decided to explore the possibility of using a Spinner component which can also have scope of both App level as well as Component level. I decided to reuse the same component but with some slight code modification.</p><p>Here is what I did:</p><ol><li>Created another div with styling position: absolute inside spinner.component.html . I added a template tag #componentSpinner</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dee1080d7cc9d19b651a447df6948e75/href">https://medium.com/media/dee1080d7cc9d19b651a447df6948e75/href</a></iframe><p>2. I removed #componentSpinner from visibility using display:none , so that it is not visible by default. To achieve that, I used AfterViewInit hook. Once I have the ElementRef , I saved it inside SpinnerService .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d20251fcc5c5a44f38c2a47cdcdcfbb4/href">https://medium.com/media/d20251fcc5c5a44f38c2a47cdcdcfbb4/href</a></iframe><p>3. Now I needed to add this template to our targetComponent on which we want to add scoped spinner. Once the loading was completed, I also needed to remove the #componentSpinner template which I added dynamically.</p><p>To handle this, I created:</p><ul><li>startLoadingForComponent(component: ElementRef)</li><li>finishLoadingForComponent(component: ElementRef)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cace15d330769a4837422c507638056/href">https://medium.com/media/0cace15d330769a4837422c507638056/href</a></iframe><p>And, that’s it!</p><p>To use it inside a component, we need to add a #template to the parent div. This would help us get the entire component HTML and add our small spinner code to it.</p><p>In our use, we can have an app that has a DashboardComponent . The <strong>Dashboard component</strong> may call several APIs and it can also have a few small components such as OrderCountComponent &amp; UserCountComponent . These components may depend on DashboardComponent to get some @Input data or they can independently make API calls inside them.</p><p>We can use the SpinnerComponent scoped to UserCountComponent by adding #userTemplate to its parent div</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/412dcc485304c6ca94ced667a6265079/href">https://medium.com/media/412dcc485304c6ca94ced667a6265079/href</a></iframe><p>And, using the ElementRef to show spinner on the component level as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a565ca74cdd7c687bd68668f8d2076b/href">https://medium.com/media/2a565ca74cdd7c687bd68668f8d2076b/href</a></iframe><p>I have added some intensional delays to mock slow network calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*voZ9mEDeWm_SM7mA3Nnz5A.gif" /></figure><p>I know it may not be a good fit for all use cases, but it extended the feature of existing SpinnerComponent . If you liked the idea or to improve it further, feel free to drop me a note. For me, it was a fun and unique implementation.</p><p>You can refer to the final code in <a href="https://github.com/shashankvivek/">my github profile</a> as <a href="https://github.com/shashankvivek/scoped-spinner">scoped-spinner</a> project.</p><blockquote>If you liked what you read, please 👏 👏 clap 👏 👏 few times to encourage me 🐼 for writing such articles. Cheers !!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f8dd3e191c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[InfluxDB 2.X — A quick hands-on intro to timeseries DB]]></title>
            <link>https://shashankvivek-7.medium.com/influxdb-2-x-a-quick-hands-on-intro-to-timeseries-db-8101bb92dac6?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8101bb92dac6</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[influxdb]]></category>
            <category><![CDATA[timeseries-database]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Sun, 10 Jan 2021 18:40:41 GMT</pubDate>
            <atom:updated>2021-01-11T05:31:20.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>InfluxDB 2.X — A quick hands-on intro to timeseries DB</h3><p>In today’s world where data is the new oil, we are often lured into collecting all forms of data. Once we have those data, the next step comes as the visualization of the data to make some sense out of it. One such data which is associated with time stamps are stored in timeseries database (TMDB).</p><p>In TMDB, the time is treated as first class citizen. Recording each and every change to the system as a new, different row is what makes time-series data so powerful. It allows us to measure and analyze change: what has changed in the past, what is changing in the present, and what can we forecast changes may look like in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QePvkDVkr7bcdgnOzeYyAQ.jpeg" /></figure><p>Now, the first question comes into our mind is</p><blockquote><strong>Why so we need a dedicated timeseries database ? Can’t we use any existing DBs ?</strong></blockquote><blockquote>The reason has been explained <a href="https://www.influxdata.com/time-series-database/">here </a>very clearly.</blockquote><blockquote><strong>Note</strong>: InfluxDB is NoSQL based TMDB, there are TMDBs which are based on relational model such as <a href="https://www.timescale.com/"><strong>TimescaleDB</strong></a><strong>.</strong></blockquote><p>Before we proceed further, I would like to highlight that there are breaking changes if you are coming from 1.x to 2.x version. Covering all the differences is a different topic all together which should be handled separately. One major thing which you’ll notice is introduction of <a href="https://docs.influxdata.com/influxdb/v2.0/query-data/get-started/">flux</a> in 2.X.</p><p>As a part of exercise to this article, we’ll be :</p><ul><li>Quickly setting up the InfluxDB2.0 on our local machine</li><li>Populate some sample data</li><li>Query using Flux</li></ul><h4>1. Create service using docker-compose with docker image on port as &quot;8099&quot;:</h4><blockquote>Make sure you have docker on your machine to follow through this article</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41e86205d0da3ba900918aef21300f34/href">https://medium.com/media/41e86205d0da3ba900918aef21300f34/href</a></iframe><p>Once we have created above file, run below command to run the service:</p><blockquote>docker-compose up</blockquote><p>To check the service, use http://localhost:8099</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAd4D1bv4W4ZNh0cnzxIRQ.jpeg" /></figure><h4>2. Setup user details:</h4><p>Click on “<strong>Get Started” </strong>and fill below details. With 2.x version, a user token based authentication has been added in InfluxDB. I’ll be creating a separate article to cover API based queries.</p><p>In this demo, I am using below details.</p><blockquote><strong>Organization Name</strong>: test-org</blockquote><blockquote><strong>Bucket Name</strong>: test-bucket</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDY_pY4dhL-O9oxj_FZ-aw.jpeg" /></figure><p>After clicking on “Continue” , we will be required to complete the setup. Select “<strong>Quick Start” </strong>option to do quick setting and skip setup complexities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4HH7rsEgWMKNuAZkmJkTQ.jpeg" /></figure><p>As soon as the setup is done, we’ll land on the below dashboard page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTHD4r5Ux94Jhs6KtxuO1A.jpeg" /></figure><h4>3. Check the available “Buckets”</h4><blockquote>A <strong>bucket</strong> is a named location where time series data is stored. All buckets have a <strong>retention policy</strong>, a duration of time that each data point persists. A bucket belongs to an organization.</blockquote><p>To quickly verify the <a href="https://docs.influxdata.com/influxdb/v2.0/organizations/buckets/">bucket </a>we have created earlier, we can navigate to</p><pre>Data &gt; Buckets</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uo8_xYfqnRiqayvSFIsNlQ.jpeg" /><figcaption>Navigation to buckets</figcaption></figure><h4>4. Load sample data into bucket</h4><p>To load a sample data into influxDB, we can get into the bucket by clicking on “<strong>Bucket Name</strong>” . On the next screen, we can see bunch of options to play around.</p><p>We’ll be loading the data using flux command. To run the flux commands, click on “<strong>Script Editor</strong>” as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgt2b3zFjEbpWaq4aYtOfw.jpeg" /></figure><p>Once the editor is opened, we will run below command</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebefdf68ed97a0d44819b29166781556/href">https://medium.com/media/ebefdf68ed97a0d44819b29166781556/href</a></iframe><p>A successfully loaded data will immediately show us a plotted graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VPavcQQ31SGlAzCMUD8MQ.png" /></figure><blockquote>Please note that we have mentioned the <strong>bucket </strong>and <strong>org </strong>name as created earlier.</blockquote><p>Now if we go back to “<strong>Query Builder</strong>” and refresh the page, we’ll be seeing all the fields on which can apply filtering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1hHj31nNqQao2gJlx1qIQ.png" /><figcaption>A custom query built for demo</figcaption></figure><p>The above graphical filtering can be translated into</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f275dce999a023ef858d3b0b05ac1e/href">https://medium.com/media/a9f275dce999a023ef858d3b0b05ac1e/href</a></iframe><p>That’s it for a quick setup of InfluxDB 2.X on your local machine. I hope this article will help someone new to InfluxDB TMDB.</p><blockquote>If you liked what you read, please 👏 👏 clap 👏 👏 few times to encourage me 🐼 for writing such articles. Cheers !!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8101bb92dac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Input with `debounceTime` using `tick()`— Karma-Jasmine Testing]]></title>
            <link>https://shashankvivek-7.medium.com/testing-input-with-debouncetime-using-tick-karma-jasmine-testing-bccfe8977165?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/bccfe8977165</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 07:52:49 GMT</pubDate>
            <atom:updated>2020-11-26T07:53:37.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Input with “debounceTime” using ‘tick()’— Karma-Jasmine Angular Testing</h3><p>In the world of <em>unit testing </em>in <strong>Angular</strong>, use of tick() often remains mystery unless we stumble upon its use case. I will try to explain the working of tick() using an <strong>Input</strong> element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3NJx7E2hCvgYKeEXvRybg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@olly?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Andrea Piacquadio</a> from <a href="https://www.pexels.com/photo/round-analog-clock-820735/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>To start with, lets create an HTML element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d955d4bd20ab441fcafb3ce2bdafd99b/href">https://medium.com/media/d955d4bd20ab441fcafb3ce2bdafd99b/href</a></iframe><p>and respective component.ts file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cb85e53ffa3c2b031bec2cb5606accc/href">https://medium.com/media/6cb85e53ffa3c2b031bec2cb5606accc/href</a></iframe><p>As we can see in this example, the input provided by the user will make a server call. To reduce the repeated call on every input value change (searchValChanged(event) ) , we have put a debounceTime of 1000ms<strong>.</strong></p><p>Without debounceTime below test case can easily check the behavior of code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83c4bd8d42aa1ad9f2a47475a9df0d13/href">https://medium.com/media/83c4bd8d42aa1ad9f2a47475a9df0d13/href</a></iframe><p>But, now we need to make the angular know that it needs to move ahead with testing only when 1000ms has completed its cycle. To do that , we have tick() to the rescue. The angular docs have explained <a href="https://angular.io/api/core/testing/tick">tick </a>in brief as:</p><blockquote>Simulates the asynchronous passage of time for the timers in the fakeAsync zone.</blockquote><p>This clearly matches our requirement.</p><blockquote><strong>Note</strong>: &quot;tick()” can only be used within “fakeAsync&quot; block</blockquote><p>fakeAsync gives us control over time when working with tick() .</p><p>To sum it up, the final test file would look something like :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5403d4f59f0cfb3e1f4ce1526fef2611/href">https://medium.com/media/5403d4f59f0cfb3e1f4ce1526fef2611/href</a></iframe><blockquote>You can find the complete code on my <a href="https://github.com/shashankvivek/angular-karma-playground/tree/master/karma-project/src/app/debounce-ex">github repository</a> .</blockquote><blockquote>If you like this article, please 👏 clap 👏 few times &amp; encourage me 🐼 to write more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bccfe8977165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting to know fixture.debugElement : Angular Unit Testing]]></title>
            <link>https://shashankvivek-7.medium.com/getting-to-know-fixture-debugelement-angular-unit-testing-f8389ea61f02?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8389ea61f02</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Sat, 17 Oct 2020 13:36:07 GMT</pubDate>
            <atom:updated>2020-10-17T13:40:37.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting to know fixture.debugElement : Angular Unit Testing</h3><p>In the Angular world of Unit testing, we often overlook some concepts unless we actually need them to serve specific purpose. After answering a lot of questions on <a href="https://stackoverflow.com/users/3092377/shashank-vivek">stackoverflow </a>, one of such concept is related to accessing HTML elements using fixture .</p><p>Before we begin, if you are new to unit testing then I would recommend you to start from the <a href="https://medium.com/@shashankvivek.7/say-hi-to-jasmine-karma-in-angular-intro-d728d669a1c7">intro article</a>. You can more article links below <a href="https://medium.com/@shashankvivek.7/say-hi-to-jasmine-karma-in-angular-intro-d728d669a1c7">this </a>link, which contain more use cases for unit testing in Angular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*SbhLGLIYSyRianoNmB5zRw.png" /></figure><p>In this article, I’ll discuss 3 ways to access an HTML element and how are they different. For below element with an id as shan:</p><pre>&lt;div id=&quot;shan&quot;&gt;Hey there&lt;/div&gt;</pre><p>We can use below ways to get it in unit testing:</p><ul><li>fixture.debugElement.query(By.css(&#39;#shan&#39;))</li><li>fixture.debugElement.nativeElement.querySelector(&#39;#shan&#39;)</li><li>document.getElementById(&#39;#shan&#39;)</li></ul><h4><strong>1. fixture.debugElement.query(By.css(‘#hello’))</strong></h4><p>It is used to get “<a href="https://angular.io/api/core/DebugElement">DebugElement</a>” for a DOM object. More detailed info can be found <a href="https://angular.io/api/platform-browser/By#css">here on offical Angular doc</a>.</p><p>In brief, you can pass <strong>id </strong>as By.css(&#39;#shan&#39;) , <strong>class </strong>as By.css(&#39;.shan&#39;) , or you can also elements with ways such as By.css(&#39;div&#39;) or By.css(&#39;some-app-component&#39;)</p><p>DebugElement is an Angular class that contains all kinds of references and methods relevant to investigate an <strong>element</strong> as well as <strong>component</strong></p><pre>fixture.debugElement.query(By.css(&#39;#shan&#39;))</pre><p>will return</p><blockquote><em>DebugElement__PRE_R3__{listeners: [], parent: DebugElement__PRE_R3__{listeners: [], parent: null, </em>debugContext: DebugContext<em>{view: …, nodeIndex: …, nodeDef: …, elDef: …, elView: …}, nativeNode: Hey there, properties: Object{}, attributes: Object{ng-version: …}, classes: Object{}, styles: Object{}, childNodes: […], nativeElement: Hey there}, </em>debugContext: DebugContext<em>{view: Object{def: …, parent: …, viewContainerParent: …, parentNodeDef: …, context: …, component: …, nodes: …, state: …, root: …, renderer: …, oldValues: …, disposables: …, initIndex: …}, nodeIndex: 0, nodeDef: Object{nodeIndex: …, parent: …, renderParent: …, bindingIndex: …, outputIndex: …, checkIndex: …, flags: …, childFlags: …, directChildFlags: …, childMatchedQueries: …, matchedQueries: …, matchedQueryIds: …, references: …, ngContentIndex: …, childCount: …, bindings: …, bindingFlags: …, outputs: …, element: …, provider: …, text: …, query: …, ngContent: …}, elDef: Object{nodeIndex: …, parent: …, renderParent: …, bindingIndex: …, outputIndex: …, checkIndex: …, flags: …, childFlags: …, directChildFlags: …, childMatchedQueries: …, matchedQueries: …, matchedQueryIds: …, references: …, ngContentIndex: …, childCount: …, bindings: …, bindingFlags: …, outputs: …, element: …, provider: …, text: …, query: …, ngContent: …}, elView: Object{def: …, parent: …, viewContainerParent: …, parentNodeDef: …, context: …, component: …, nodes: …, state: …, root: …, renderer: …, oldValues: …, disposables: …, initIndex: …}}, nativeNode: Hey there, properties: Object{}, attributes: Object{id: ‘shan’}, classes: Object{}, styles: Object{}, childNodes:[DebugNode__PRE_R3__{listeners: …, parent: …, _debugContext: …, ..nativeNode: …}], nativeElement: Hey there, name: ‘div’}</em></blockquote><h4><strong>2. fixture.debugElement.nativeElement.querySelector(‘#shan’)</strong></h4><p>nativeElement returns a reference to the DOM element which can also come under debugElement as stated above.You can use it do actions such as click() event in test cases.</p><pre>fixture.debugElement.nativeElement.querySelector(&#39;#shan&#39;).click(); // this will create a click event over this element.</pre><p>It works for querying both <strong>class </strong>something like (fixture.debugElement.nativeElement.querySelector(&#39;.shan&#39;)) as well as <strong>id</strong>.</p><pre>fixture.debugElement.nativeElement.querySelector(&#39;#shan&#39;)</pre><p>will return</p><pre>&lt;div _ngcontent-a-c0=&quot;&quot; id=&quot;shan&quot;&gt;Hey there&lt;/div&gt;</pre><h4>3. <strong>document.getElementById(‘shan’)</strong></h4><p>This is our good old way to access an id (not a class). You can&#39;t access class by doing something like</p><pre>document.getElementById(&#39;.shan&#39;) // will return null</pre><p><strong>Also, note that you don’t need to pass </strong><strong># in this function argument</strong>.</p><pre>document.getElementById(&#39;#shan&#39;) // will return null</pre><p>It should be avoided while working with angular because angular has its own ChangeDetection which requires it to be worked with fixtures. By directly calling document , you&#39;ll end up banging your head on the wall , trying to figure out <em>why is the element coming as </em><em>null</em></p><pre>document.getElementById(&#39;shan&#39;)</pre><p>will return</p><pre>&lt;div _ngcontent-a-c0=&quot;&quot; id=&quot;shan&quot;&gt;Hey there&lt;/div&gt;</pre><blockquote>If you like this article, please 👏 clap 👏 few times &amp; encourage me 🐼 to write more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8389ea61f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Go-swagger service using Google Kubernetes Engine (GKE)]]></title>
            <link>https://shashankvivek-7.medium.com/deploying-a-go-swagger-service-using-google-kubernetes-engine-gke-d6a6216b8299?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6a6216b8299</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[google-kubernetes-engine]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 16:27:31 GMT</pubDate>
            <atom:updated>2020-09-14T16:27:31.513Z</atom:updated>
            <content:encoded><![CDATA[<p>There are several ways to deploy a Go app on Google Cloud. You can use App Engine, GCE or GKE. In this tutorial, we’ll be focusing on GKE to deploy our go-swagger project. A basic Go project can easily be deployed using the examples available on <a href="https://cloud.google.com/kubernetes-engine/docs/quickstarts/deploying-a-language-specific-app">GCP documentation</a> . But in case of go-swagger, even a <a href="https://github.com/shashankvivek/demo-go-service">basic project</a> requires lot of dependencies along with below command to run it as server:</p><pre>go run cmd\e-food-server\main.go --scheme http --port=8080</pre><p>In this tutorial, I will cover on the steps to deploy my <a href="https://github.com/shashankvivek/demo-go-service">github project </a>on GKE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpeYLJdSGQxXGnEQPLCTjw.jpeg" /></figure><p>To start with, you need to have a GCP project configured along with billing details. Once we have that checked, we can jump to Cloud Shell and setup GCP project ID using command:</p><blockquote>gcloud set config set project $YOUR_PROJECT_ID</blockquote><p>Let’s break it down as steps which will actually be self explanatory with the help of images.</p><p><strong>Step 1: Export all variables which will to be used later:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUjMCiH-BojWIKODYHUADA.png" /></figure><p><strong>Step 2. Create GKE cluster</strong></p><p>To deploy our service, we need to start by building GKE cluster. It can be achieved using below command:</p><pre>gcloud container clusters create my-demo-gke \ <br>   — num-nodes 1 \<br>   — enable-basic-auth \ <br>   — issue-client-certificate \ <br>   — zone $my_zone</pre><p>Once executed, you can see the cluster by Navigating to <strong><em>Kubernetes → Cluster </em></strong>from GCP menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1okMZNkJjTvcbc8BgON9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*c0-ljBsKc2ECzOx59svaSQ.png" /></figure><p><strong>Step 3: Clone the target repository and download all dependencies</strong></p><p>Now that we have our cluster created, we need to clone the <a href="https://github.com/shashankvivek/demo-go-service">github repo</a> in the cloud shell. We’ll be using below command to get the project which I have created</p><pre>git clone <a href="https://github.com/shashankvivek/demo-go-service.git">https://github.com/shashankvivek/demo-go-service.git</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-Q4fXl-x4FMH_3ogdJ5_A.png" /></figure><p><strong><em>Later navigate to the project directory</em></strong> &amp; download all dependencies using:</p><pre>go get ./...</pre><p><strong>Step 4: Create binaries</strong></p><p>Once we have our dependencies downloaded, we need create the binary file which we’ll be later using for deploying with the help of Docker image and pushing it to GCP Container Registry.</p><p>To build the binary, use below command:</p><pre>env CGO_ENABLED=0 GOOS=linux go build -a -o ./main ./cmd/demo-server/...</pre><blockquote><strong>Note</strong>: You’ll see that we setting up few values and then doing go build . The reason for that can be explained in <a href="https://stackoverflow.com/questions/51508150/standard-init-linux-go190-exec-user-process-caused-no-such-file-or-directory/62123648#62123648">this stackoverflow post</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhMj4pJKzLjUsKzJL5PQaA.png" /></figure><p><strong>Step 5: Create docker image</strong></p><p>Once the binaries are created, we need to create a docker image which can be pushed to Container Registry. Here we are using latest tag but in real world, it can be combination of branchName-buildNumber to make all images unique.</p><pre>docker build -f &quot;./Dockerfile&quot; -t gcr.io/$proj_id/my-demo-gke:latest .</pre><p>The given <a href="https://github.com/shashankvivek/demo-go-service/blob/master/Dockerfile">Dockerfile </a>has 6 steps which basically downloads an alpine image, copies the binary file, expose 8080 port of Docker image and the runs the binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcvoZLX7AVisTrkA9VIw0A.png" /></figure><p>To test the docker file, we can even run it on cloud shell using below command:</p><pre>docker run -it gcr.io/$proj_id/my-demo-gke:latest sh</pre><p><strong>Step 6: Push docker image to GCP</strong></p><p>After successfully building the docker image, the next step is to push it to Container Registry.</p><pre>gcloud docker -- push gcr.io/$proj_id/my-demo-gke:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4MIWcx2LpJkQ__dLYe9Lg.png" /></figure><p>We can cross check the image by getting into <strong><em>Side Panel → Cloud Registry</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGs8bNZaMfvAcGcXuD6oCg.png" /></figure><p><strong>Step 7: Create deployment</strong></p><p>Now that we have our cluster and image ready. The next step is to deploy the image. To do that, I have a <a href="https://github.com/shashankvivek/demo-go-service/blob/master/deployment.yaml">deployment.yaml</a> file which takes care of that. Please make sure to replace PROJECT_ID in <a href="https://github.com/shashankvivek/demo-go-service/blob/master/deployment.yaml">deployment.yaml</a> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab29e504ac42a5dd19a200b66638b6f0/href">https://medium.com/media/ab29e504ac42a5dd19a200b66638b6f0/href</a></iframe><p>To make the deployment , we just need to run</p><pre>kubectl apply -f deployment.yaml</pre><p>This deployment will create one POD and add respective selectors and labels to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUaMjkKbdPeBjQGKjQV_1A.png" /></figure><p>We can confirm the deployment status by going to <strong><em>Workloads</em></strong> section of GKE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*cD8q-1MpIpXnpDyOtOCENg.png" /></figure><p><strong>Step 8: Expose the deployment using GKE service</strong></p><p>Just deploying the code is not enough, we need to provide a port and IP so that we can access it. To do that , we’ll be using <a href="https://github.com/shashankvivek/demo-go-service/blob/master/service.yaml">GKE service</a> of type LoadBalander .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9762d77aa2d88a0733d9d1a13c128a15/href">https://medium.com/media/9762d77aa2d88a0733d9d1a13c128a15/href</a></iframe><p>To create the LoadBalancer service, we need to run below command:</p><pre>kubectl apply -f service.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJWJVA_DA0NdkcSAHoLAMQ.png" /></figure><p>Once created, we can cross check the status of service under <strong><em>Service &amp; Ingress</em></strong> . IT may take upto 60 secs to get the service up and running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qM4J7ALSSIw20JGE3mVQzA.png" /></figure><p><strong>Step 9: Accessing the Endpoint</strong></p><p>Now that we have created a load balancer serive, We can go to externally exposed IP which can be found under External endpoints section of it. Refer below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*BxAHtojM0htFuVjISWRvvw.png" /></figure><blockquote>At last, we can see the deployed code on an external endpoint as below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*qzBbR8VXJWYyHALWDMPhsw.png" /></figure><p>We can compare the output to local code to confirm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UboCNJdAdWofciS31UFWQ.png" /></figure><p>I hope this article will be helpful to people who are new to GKE as well as go-swagger. I had my own learning curve so I decided to collect all the information in this one article. Cheers 🍹</p><blockquote>If you like this article, please 👏 clap 👏 few times to encourage me 🐼 to write more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6a6216b8299" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go lang: Defining Struct Methods With & Without Pointers]]></title>
            <link>https://shashankvivek-7.medium.com/go-lang-defining-struct-methods-with-without-pointers-ed6d07733657?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed6d07733657</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 15:54:14 GMT</pubDate>
            <atom:updated>2020-08-31T15:54:14.086Z</atom:updated>
            <content:encoded><![CDATA[<p>I started my backend career in Java. Coming from Java as an Object Oriented Language, I had a keen interest in knowing the object oriented implementation in <strong>Go</strong>. The implementation was very relatable using struct to achieve <strong>OOP</strong>. That’s when, I saw a subtle way of how Go achieved it in 2 ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnnkReGamr7ps_2HlGT_FQ.png" /></figure><h4>1. Pointer Struct Methods</h4><p>In this implementation, we will see that the struct is followed by * (pointers) in its associated methods. We have created a Employee struct and have created a private field named name which is set using a method named SetName(name string).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/758bcf5d4b3948b42576e536f53b1512/href">https://medium.com/media/758bcf5d4b3948b42576e536f53b1512/href</a></iframe><p>When we run the code, we’ll see that the name property of emp1 has been set successfully to Vivek.</p><p><a href="https://play.golang.org/p/NqllOG1OJqN">The Go Playground</a></p><h4>2. Value Struct Methods</h4><p>For value struct methods, we’ll try the same code but with no * (pointer) .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b439ed801483056fb456bf4657895879/href">https://medium.com/media/b439ed801483056fb456bf4657895879/href</a></iframe><p>If we run this code, we’ll see that the output is Shashank and not Vivek as we saw in pointer method.</p><p><a href="https://play.golang.org/p/LEBLxBwx0DH">The Go Playground</a></p><p>This clearly reflects the actual working of pointer were the values are referred using memory address. Hence, any change in value by reference changes the actual variable emp1 for <strong>Pointer Methods</strong>.</p><p>This implies that for creating an immutable object, we should use Value Method which won’t change the object, rather we can return a new copy of variable making it immutable. Where as, if we want to modify the variable itself, Pointer Method is the way to go.</p><blockquote>If you like this article, please 👏 clap 👏 few times to encourage me 🐼 to write more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed6d07733657" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go-Swagger : User Authentication & securing API using JWT — Part 2]]></title>
            <link>https://shashankvivek-7.medium.com/go-swagger-user-authentication-securing-api-using-jwt-part-2-c80fdc1a020a?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/c80fdc1a020a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 17:24:52 GMT</pubDate>
            <atom:updated>2020-08-13T17:24:52.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go-Swagger : User Authentication &amp; securing API using JWT — Part 2</h3><p>This article is the continuation of <a href="https://medium.com/@shashankvivek.7/go-swagger-user-authentication-securing-api-using-jwt-part-1-6e2a0ab8c721">user authentication using JWT</a> . In Part-1 of this article, we successfully generated a <strong>valid JWT </strong>token using our /login endpoint. In this section, we’ll work on securing APIs so that it restricts any unauthenticated calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5nH7yexoT8DkdnZ-UfxDw.png" /></figure><h4>1. Define security in swagger.yaml</h4><p>To enable authentication for an API, we need to define securityDefinitions into swagger.yaml file:</p><pre>securityDefinitions:  <br>   Bearer:    <br>     type: apiKey    <br>     name: Authorization    <br>     in: header</pre><h4>2. Create restricted API</h4><p>Lets create an endpoint, say /user/cart which fetches all cart items of a registered user. Since , we want to restrict this API for authorized user only, we need to add below definition in swagger.yaml file under /user/cart yaml property.</p><pre>security:<br>  - Bearer: []</pre><p>The final swagger.yaml file will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d66128dcda25eb21d5ce100ef60ef19/href">https://medium.com/media/1d66128dcda25eb21d5ce100ef60ef19/href</a></iframe><p>You view this yaml <a href="https://editor.swagger.io/">online on swagger editor</a>, note the “<strong>Lock</strong>” icon on /user/cart . It informs a developer that this API needs authorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*QxKJgOIu2h93gZNHDB0jpw.png" /></figure><h4>3. Generate boilerplate code from swagger.yaml</h4><p>To generate the code from the above swagger.yaml file, you’ll have run below command:</p><blockquote>swagger generate server -f swagger.yaml --default-scheme http --exclude-main</blockquote><h4>4. Create authentication middleware</h4><p>Now, that we have the required code generated based on the swagger.yaml file, we can proceed on creating a middleware which would intercept all those API calls that has security defined under it. We’ll be doing below steps to get it done:</p><ul><li>Create authenticator.go , which will validate the JWT token. If the token is valid, we return the email and error as nil. For any invalid token, we’ll return an error .</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e085473bbeaa187b791951408bd796/href">https://medium.com/media/c5e085473bbeaa187b791951408bd796/href</a></iframe><ul><li>In <a href="https://github.com/shashankvivek/e-food-server/blob/5a9ba29511dd9ddb13bf472ed083f9313392653f/api/restapi/configure_e_food.go#L45">configure_e_food.go</a> file, we’ll attach ValidateHeader as middleware.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d847d5dbfe4d93c12673e9197358f7a/href">https://medium.com/media/8d847d5dbfe4d93c12673e9197358f7a/href</a></iframe><blockquote><strong><em>That’s it ! </em></strong>👑</blockquote><p><strong><em>Now, the </em></strong><strong><em>/user/cart can only be accessed by a valid </em></strong><strong><em>JWT token.</em></strong></p><h4>5. Getting User info from JWT Token in API code.</h4><p>As I have already explained the during the <a href="https://medium.com/@shashankvivek.7/go-swagger-a-go-web-framework-worth-learning-af0e9ed75343?source=---------5------------------">intro article of </a><a href="https://medium.com/@shashankvivek.7/go-swagger-a-go-web-framework-worth-learning-af0e9ed75343?source=---------5------------------">go-swagger</a> , We’ll be similarly creating get_user_cart_item.go . We can re-use ValidateHeader() from utils package and use it extract <strong>email</strong> . Once we have the email, we can pass it on to GetCustomerCart() to get the respective cart items.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea3df0b9ffa6d87f0c9db44d80ecf277/href">https://medium.com/media/ea3df0b9ffa6d87f0c9db44d80ecf277/href</a></iframe><p>To test this endpoint , we need to generate a token using /login endpoint. Once we have the token, we need add it in Authorization header .</p><p>Screenshot of a Valid request :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhKbBsW4xNLuTD9EaIGGxQ.png" /></figure><p>Screenshot of a Invalid request with expired token :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNu9WytVzM9cNKq69ochwQ.png" /></figure><p>The final code can be referred in my <a href="https://github.com/shashankvivek/e-food-server">e-food GitHub</a> repository. Feel free to explore the repository. It is a working code with no change in file names.</p><blockquote>If you like this article, please 👏 clap 👏 few times to encourage me 🐼 to write more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c80fdc1a020a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go-Swagger : User Authentication & securing API using JWT — Part 1]]></title>
            <link>https://shashankvivek-7.medium.com/go-swagger-user-authentication-securing-api-using-jwt-part-1-6e2a0ab8c721?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2a0ab8c721</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 08:41:56 GMT</pubDate>
            <atom:updated>2020-08-13T17:26:05.802Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go-Swagger : User Authentication &amp; securing API using JWT — Part 1</h3><p>In my previous article, I have explained on <a href="https://medium.com/@shashankvivek.7/go-swagger-a-go-web-framework-worth-learning-af0e9ed75343">how to register a new user</a> for a website. We saved our password securely using bcrypt into the database which is a sensitive data. Once, we are done with registration, the next step is to provide login for the registered user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5nH7yexoT8DkdnZ-UfxDw.png" /></figure><blockquote>If you are new to go-swagger, I would recommend you to read the <a href="https://medium.com/@shashankvivek.7/go-swagger-a-go-web-framework-worth-learning-af0e9ed75343">introduction</a> and <a href="https://medium.com/@shashankvivek.7/go-swagger-structuring-implementing-apis-afd7098b0e7">implementation</a> part of this amazing framework.</blockquote><p>For user authentication we have few options such as session or JWT (<em>JSON Web Token</em>) based authentication. I will not get into much details of each, but I’ll explain the reason of choosing JWT over session briefly.</p><h3>JWT Vs Session based Authentication:</h3><p>Major reason for choosing JWT over session is because the <strong><em>JWT is purely stateless</em></strong>. With stateless, I mean that they can be used by server which has multiple instance of backend services running. With session you will have separate session for each service instance. Hence, if the load balancer redirects call to a service where the session info of the user is not present, then the server won’t be able to authenticate the user.</p><p>To overcome the session sharing there are few ways but that would go beyond the scope of this article.</p><p>With JWT , the server issues a token to the client(user) after successful login. Once the token is issued by server, it is stored on the client side and is added as Authorization in the headers to get access to protected API calls.</p><blockquote><strong>Dummy</strong><strong>JWT</strong> : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9<strong>.</strong>eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ<strong>.</strong>SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</blockquote><p>The structure of JWT consists of <strong>Header, Payload </strong>&amp; <strong>Signature </strong>separated by dot (“<strong>.</strong>”) which can be decoded using <a href="https://jwt.io/">jwt.io</a> site. Getting into more details of JWT will again be out of scope for this article, so I’ll try to write a small article on JWT and link it here later.</p><p>Now, that we have some idea about JWT, we can start working on our <a href="https://github.com/shashankvivek/e-food-server">small ecommerce</a> website to have user authentication. Lets go step by step:</p><h4>1. Create “/login” endpoint for authentication</h4><p>To create the /login endpoint, we’ll follow the same steps which we followed <a href="https://medium.com/@shashankvivek.7/go-swagger-a-go-web-framework-worth-learning-af0e9ed75343">earlier</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfdb38fe5e9ea19a5b093bd1ca926ca3/href">https://medium.com/media/dfdb38fe5e9ea19a5b093bd1ca926ca3/href</a></iframe><p>You can visualize the API by pasting it <a href="https://editor.swagger.io/">online swagger editor</a> . Please note that we’ll be getting token as a response (type LoginSuccess in swagger.yaml) of this endpoint.</p><h4>2. Generate Boilerplate go-swagger code for the endpoint :</h4><p>Once we have the /login endpoint created in swagger.yaml, we will generate the respective boilerplate code using:</p><pre><em>swagger generate server -f api/swagger.yaml --default-scheme http</em></pre><p>This results in creating in below files <em>boilerplate</em> files:</p><ul><li>/models/login_info.go</li><li>/models/login_success.go</li><li>/restapi/operations/user/login.go</li><li>/restapi/operations/user/login_parameters.go</li><li>/restapi/operations/user/login_responses.go</li><li>/restapi/operations/user/login_urlbuilder.go</li></ul><p>But we should not be worried about these files as they are generated based on swagger.yaml</p><h4>3. Code Implementation:</h4><p>To integrate boilerplate code with our custom code, we need to create a handler file login.go under ./handler folder &amp; a dao package to access user details from MySql .</p><blockquote>This project structure which we are discussing, has already been explained <a href="https://medium.com/@shashankvivek.7/go-swagger-structuring-implementing-apis-afd7098b0e7https://medium.com/@shashankvivek.7/go-swagger-structuring-implementing-apis-afd7098b0e7">previously</a>. Also, To access login details from Database, we’ll be using the same code structure to create mysql client as we have <a href="https://medium.com/@shashankvivek.7/go-swagger-user-registration-with-mysql-go-80684f5f2505?source=your_stories_page---------------------------">done for user registration</a> in one of my articles.</blockquote><ul><li>We’ll create a DAO package which will interact with MySQL database. Please note that we’ll be injecting the *sql.DB connection pointer into the FetchUserDetails() to keep the code loosely coupled.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35ea13178937a18a9e3b71a2aec19774/href">https://medium.com/media/35ea13178937a18a9e3b71a2aec19774/href</a></iframe><ul><li>Create a utils/authenticator.go file, which we’ll be using to generate JWT token once the password is matched successfully. The below code uses HMAC-SHA as jwt.SigningMethodHS256 . We also added <strong>user details</strong> under claims such as email , first_name , last_name and an expiration time of 300 minutes for the generated token. The token is signed and returned.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07947047e4c0662a8384ad8269023cb9/href">https://medium.com/media/07947047e4c0662a8384ad8269023cb9/href</a></iframe><ul><li>Creating login.go to access dao/customer.go &amp; utils/authenticator.gofile. The login.go will perform below operations:</li></ul><ol><li>Fetch User details from MySql database.</li><li>Since we have <a href="https://medium.com/@shashankvivek.7/go-swagger-user-registration-with-mysql-go-80684f5f2505">encrypted the password </a>using bcrypt , we’ll the same package to the <em>compare the login password with encrypted password</em>.</li><li>Once it matches, we create a signed token using utils.GenerateJWT()</li><li>return the response LoginSuccess (as defined in swagger.yaml)</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f858ed0d5ccadeebe9a69bf29d0c177/href">https://medium.com/media/4f858ed0d5ccadeebe9a69bf29d0c177/href</a></iframe><h4>4. Wire-up the endpoint with handler</h4><p>To finally execute login.go when we call /login endpoint, We need to go to configure_e_food.go file and assign NewUserLoginHandler with dbclient:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aadb76df5ce35bd7554a1574b6c0c840/href">https://medium.com/media/aadb76df5ce35bd7554a1574b6c0c840/href</a></iframe><h4>5. Hit Endpoint to get the token</h4><p>Once we have the /login endpoint created and /register <a href="https://medium.com/@shashankvivek.7/go-swagger-user-registration-with-mysql-go-80684f5f2505">endpoint for registering a new user</a>, spin up the localhost server with</p><blockquote><em>go run cmd\e-food-server\main.go — scheme http — port=8080</em></blockquote><p>Try the postman to get output as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaWlkjTCNs8af_NjTpMT2g.png" /></figure><p>The output token can be <a href="https://jwt.io/">decoded</a> to know all the details which we have added on server side using authenticator.go file.</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRob3JpemVkIjp0cnVlLCJleHAiOjE1OTY5Nzc2MjEsImZuYW1lIjoiU2hhbiIsImxuYW1lIjoiVml2IiwidXNlciI6ImFzZEB0ZXN0LmNvbSJ9.tdhUL-KpDmzSNtV9z6XhUgoTKcVabuOPS3fHAySjSXQ</pre><blockquote>Make sure to check mark “secret base64 encoded” to view the details on <a href="https://jwt.io/">jwt.io</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCMYiBSjUKthPt4dIHrdBQ.png" /></figure><p>That’s it for this article, in my <a href="https://medium.com/@shashankvivek.7/go-swagger-user-authentication-securing-api-using-jwt-part-2-c80fdc1a020a">next article</a> I’ll show how to restrict the API calls so that they are only accessible using the valid JWT token. In case you want a final structured code, you can refer to the demo <a href="https://github.com/shashankvivek/e-food-server">e-food-server</a> code base .</p><p>I hope that this will help someone who is new with go-swagger and wants to implement user authentication. You can use the logic of login.go and authenticator.go in a normal <strong>Go </strong>app as well, I have just used it as per go-swagger framework.</p><blockquote>If you like this article, please 👏 clap 👏 few times to encourage me 🐼 to write more.</blockquote><p><a href="https://medium.com/@shashankvivek.7/go-swagger-user-authentication-securing-api-using-jwt-part-2-c80fdc1a020a">Go-Swagger : User Authentication &amp; securing API using JWT — Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2a0ab8c721" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go-Swagger: User Registration with MySql & Go]]></title>
            <link>https://shashankvivek-7.medium.com/go-swagger-user-registration-with-mysql-go-80684f5f2505?source=rss-41c54a11f4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/80684f5f2505</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[bcrypt]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Shashank Vivek]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 10:36:59 GMT</pubDate>
            <atom:updated>2020-08-09T08:48:58.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Go has really gained a lot of momentum in the market. Combining Go with swagger using <a href="https://goswagger.io/"><strong>go-swagger</strong></a>, makes it a very powerful yet simple web framework to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*bqiDv-5vD-IEgBdbJ4iUTQ.jpeg" /></figure><p>If you are new to <strong>go-swagger</strong> then I’ll strongly recommend to read <a href="https://medium.com/@shashankvivek.7/go-swagger-a-go-web-framework-worth-learning-af0e9ed75343">my introductory article</a>. In the intro, I have explained the steps to install go-swagger on your local machine. Later you can refer the implementation part in <a href="https://medium.com/@shashankvivek.7/go-swagger-structuring-implementing-apis-afd7098b0e7?source=your_stories_page---------------------------">another article</a> of mine. If you have this knowledge, then you can skip and go ahead in this article.</p><h4>Prerequisite:</h4><ul><li>Install MySql into your machine and create a schema named ecommerce . Have username and password as root (you can change it as well, but make sure you make necessary change in client_builder.go as shown below )</li><li>Run below SQL <a href="https://github.com/shashankvivek/e-food-server/blob/5a9ba29511dd9ddb13bf472ed083f9313392653f/resources/create.sql#L138">query </a>in ecommerce schema to create <strong>TABLE</strong>:</li></ul><pre><em>CREATE TABLE </em>`ecommerce`.`customer`<br>(<br>    `customerId` <em>INT          NOT NULL AUTO_INCREMENT</em>,<br>    `firstName`  <em>VARCHAR</em>(45)  <em>NOT NULL</em>,<br>    `lastName`   <em>VARCHAR</em>(45)  <em>NULL</em>,<br>    `phoneNo`    <em>INT          NULL</em>,<br>    `password`   <em>VARCHAR</em>(10) <em>NULL</em>,<br>    `email`      <em>VARCHAR</em>(60)  <em>NOT NULL</em>,<br>    <em>PRIMARY KEY </em>(`email`),<br>    <em>UNIQUE INDEX </em>`phoneNo_UNIQUE` (`phoneNo` <em>ASC</em>) <em>VISIBLE</em>,<br>    <em>UNIQUE INDEX </em>`id_UNIQUE` (`customerId` <em>ASC</em>) <em>VISIBLE<br></em>);</pre><h4>Step 1: Create swagger file</h4><p>To start with the development of this new endpoint, you need to recognize the model of request &amp; response and define them inswagger.yaml file as below :</p><ol><li>/register endpoint which is of type POST .</li><li>Created request payload model named RegisterUser which containes email, fname , lname , password &amp; phoneNo .</li><li>Created response payload model named SuccessResponse .</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/662b188d9a7e4e8c4340a7896c8df126/href">https://medium.com/media/662b188d9a7e4e8c4340a7896c8df126/href</a></iframe><blockquote>You can copy-paste &amp; use <a href="https://editor.swagger.io/">online swagger editor </a>to visualize this swagger file</blockquote><h4>Step 2: Generate boilerplate code using swagger file</h4><p>Once we have the swagger.yaml file ready, we can use below command to generate the swagger generated code:</p><blockquote>swagger generate server -f swagger.yaml --default-scheme http --exclude-main</blockquote><blockquote>For better visualization, you can refer to the final code which I have created using these steps, in <a href="https://github.com/shashankvivek/e-food-server">my GitHub e-commerce server code</a> . In the GitHub code, I have kept the swagger.yaml under <a href="https://github.com/shashankvivek/e-food-server/tree/master/api">/api folder</a>. You need to go into /api folder and run swagger generate command as mentioned above.</blockquote><h4>Step 3: Install MySql package and shareable DB connection</h4><ul><li>Install Mysql go package using</li></ul><pre>go get -u github.com/go-sql-driver/mysql</pre><ul><li>Create a client_builder.go under clients folder &amp; import mysql connection driver and to use it across all endpoints.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d476fbc4922896dea29e73955b567978/href">https://medium.com/media/d476fbc4922896dea29e73955b567978/href</a></iframe><ul><li>Navigate to api/restapi/configure_e_food.go and go to func configureAPI() to create a connection client object as below:</li></ul><pre><em>func </em>configureAPI(api *operations.EFoodAPI) http.Handler {<br>  clientBuilder := clients.NewClientBuilder()<br>  dbClient := clientBuilder.BuildSqlClient() // dbClient can be injected to APIs<br>  // .... remaining code here<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZd1BUb0qs6nwjeMUBu%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZd1BUb0qs6nwjeMUBu%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZd1BUb0qs6nwjeMUBu%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aee6d4132d0252a6bd0bf66af21d793/href">https://medium.com/media/8aee6d4132d0252a6bd0bf66af21d793/href</a></iframe><h4>Step 4: Create DAO struct to manage Customer details</h4><ul><li>Create ./pkg/dao/customer.go file with a function to insert new user details</li><li>Since we want to save password in Database without exposing to other users as well as system admins, we’ll be encrypting it using bcrypt package. To install bcrypt , we can run below command:</li></ul><pre>go get -u golang.org/x/crypto/bcrypt</pre><ul><li>Below is the final code which uses bcrypt to encrypt the user password.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604027d0403475474068764671387d67/href">https://medium.com/media/604027d0403475474068764671387d67/href</a></iframe><blockquote>Note : The <strong>*models.RegisterUser</strong> type in the args has been created by swagger.yaml when we ran swagger generator command.</blockquote><h4>Step 5: Attach DAO function with Endpoint</h4><p>Now, that we have all the code in place, we can simply wireup the RegisterNewUser function with /register endpoint. To do that:</p><ul><li>Create ./handlers/post_register_user.go file and write code as below. The final code with Dependency Injected can be found <a href="https://github.com/shashankvivek/e-food-server/blob/master/handlers/post_resigter_user.go">here</a>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b5d10fdea02bf761fcfb6d323299f56/href">https://medium.com/media/4b5d10fdea02bf761fcfb6d323299f56/href</a></iframe><blockquote>Are you wondering what just happened in this code ? Check out this <a href="https://medium.com/@shashankvivek.7/go-swagger-structuring-implementing-apis-afd7098b0e7?source=your_stories_page---------------------------">article of mine</a> to understand the project structuring.</blockquote><ul><li>Go to <a href="https://github.com/shashankvivek/e-food-server/blob/5a9ba29511dd9ddb13bf472ed083f9313392653f/api/restapi/configure_e_food.go#L73">configure_e_food.go</a> file and write api.UserRegisterHandler:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92783a680dcf73b36043ba1d79cbd76a/href">https://medium.com/media/92783a680dcf73b36043ba1d79cbd76a/href</a></iframe><h4>Step 6: Make HTTP call to get response</h4><p>Run the code using :</p><blockquote>go run cmd\e-food-server\main.go — scheme http — port=8080</blockquote><p>Go to postman and try hitting POST endpoint <a href="http://127.0.0.1:8080/v1/register"><strong>http://127.0.0.1:8080/v1/register</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADTUQpzBmdJJJdFnQ94dmg.png" /></figure><p>And that’s it !</p><p>In my next tutorial (coming soon …) , I’ll show you how to login using JWT for the registered user</p><p>To explore authentication of the registered user, you can read below article</p><p><a href="https://medium.com/@shashankvivek.7/go-swagger-user-authentication-securing-api-using-jwt-part-1-6e2a0ab8c721">Go-Swagger : User Authentication &amp; securing API using JWT — Part 1</a></p><p>If you liked what you read, please 👏 👏 clap 👏 👏 few times to encourage me 🐼 for writing such articles. Cheers !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80684f5f2505" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>