<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aditya Padhi</title>
    <description>The latest articles on DEV Community by Aditya Padhi (@adityapadhikbl).</description>
    <link>https://dev.to/adityapadhikbl</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F211762%2F4042ac30-aab4-45f7-95bb-ede61182d1bb.png</url>
      <title>DEV Community: Aditya Padhi</title>
      <link>https://dev.to/adityapadhikbl</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/adityapadhikbl"/>
    <language>en</language>
    <item>
      <title>Throttle API calls</title>
      <dc:creator>Aditya Padhi</dc:creator>
      <pubDate>Sun, 25 Apr 2021 09:58:32 +0000</pubDate>
      <link>https://dev.to/adityapadhikbl/throttle-api-calls-5eh1</link>
      <guid>https://dev.to/adityapadhikbl/throttle-api-calls-5eh1</guid>
      <description>&lt;p&gt;Sometimes the server may have a limitation to respond to the number of API calls at the same moment.  Making 100s of concurrent calls to a single server will have an impact &amp;amp; it may be assumed as DOS attack.&lt;/p&gt;

&lt;p&gt;This can be handled if we could throttle the API calls during implementation.&lt;/p&gt;

&lt;p&gt;While throttling the API calls can still be handled from the developer's perspective, however proper checks needs to be done at load balancer or proxy to avoid any type of DOS attacks.&lt;/p&gt;

&lt;p&gt;While there are a lot of fantastic npm modules available, I thought of doing a short POC and write a simple one for my own understanding using some generators.&lt;/p&gt;

&lt;p&gt;Let me know in the comments if this is the proper approach :)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetch = require("isomorphic-fetch");
const totalPromiseLength = 5;
const requestMethod = url =&amp;gt; () =&amp;gt; fetch(url).then(response =&amp;gt; response.json());
let promiseArray = [...new Array(totalPromiseLength).keys()].map(index =&amp;gt;
  requestMethod("https://jsonplaceholder.typicode.com/todos/" + (index + 1))
);
function* chunks(arr, limit) {
  for (let i = 0; i &amp;lt; Math.ceil(arr.length / limit); ++i) {
      console.log("requested")
    yield [...arr].slice(i * limit, i * limit + limit);
  }
}

new Promise(async resolve =&amp;gt; {
  let generated = chunks(promiseArray, 2);
  let result = [];
  for (let bla of generated) {
    await Promise.all(bla.map(param =&amp;gt; param())).then(response =&amp;gt; {
        console.log('resolved')
      result = [...result, ...response];
      if (result.length === promiseArray.length) {
        resolve(result);
      }
    });
  }
}).then(response =&amp;gt; {
  console.log(response);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
    <item>
      <title>React Route Guards with Unit Testing</title>
      <dc:creator>Aditya Padhi</dc:creator>
      <pubDate>Mon, 30 Dec 2019 13:07:07 +0000</pubDate>
      <link>https://dev.to/adityapadhikbl/react-route-guards-with-unit-testing-4b06</link>
      <guid>https://dev.to/adityapadhikbl/react-route-guards-with-unit-testing-4b06</guid>
      <description>&lt;p&gt;In this blog post I would like to share my approach to create manageable Route Guards as well as to write unit test cases for that specific implementation.&lt;/p&gt;

&lt;p&gt;We will be testing Route Guards &amp;amp; the way it behaves based on the user roles.&lt;/p&gt;

&lt;p&gt;We will be using jest &amp;amp; @testing-library/react for writing unit test cases.&lt;/p&gt;

&lt;p&gt;I will also share a cleaner approach to test a component that returns redirect URL which will be helpful to test in a lot of scenarios like failed login testing, session timeout testing etc.&lt;/p&gt;

&lt;p&gt;While creating any web application there is a scenario where we need to add guards to route or prevent unauthorized access to certain URLs.&lt;/p&gt;

&lt;p&gt;There are many ways to do it, however one of the cleaner ways is to handle it on the client side.&lt;/p&gt;

&lt;p&gt;Let us take a hypothetical case where the roles are “viewer, publisher, admin”.&lt;/p&gt;

&lt;p&gt;The viewer will not have any access to the admin pages while the later will have access to all the pages.&lt;/p&gt;

&lt;p&gt;In a typical scenario when the user successfully logs into the application the server sends some information like this:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  token: 'qwqwqw',
  fullName: 'qwq ee',
  role: 'viewer'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can utilize the above response &amp;amp; create a simple route guard.&lt;/p&gt;

&lt;p&gt;Step 1 could be to store the role in localStorage in an encrypted manner using an awesome npm module pako.&lt;/p&gt;

&lt;p&gt;However in this article I am simply using local Storage.&lt;/p&gt;

&lt;p&gt;Step 2 could be to create a route guard.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import { Redirect } from "react-router";
function RouteGuard(props) {
  let userRole = localStorage.getItem("userRole") || "viewer";
  if (props.allowedRoles.indexOf(userRole) &amp;gt; -1) {
     return props.render({ userRole: userRole });
  }
  return &amp;lt;Redirect to="/unauthorized" /&amp;gt;;
}
export default RouteGuard;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this simple functional module we created a logic to check for the role &amp;amp; return the component passed to the render props of the RouteGuard component. So basically we are using render props property of React.&lt;/p&gt;

&lt;p&gt;So in index.js we can import this component &amp;amp; use it like:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Route
 path="/welcome"
 render={props =&amp;gt; (
   &amp;lt;RouteGuard
    allowedRoles={["admin", "publisher", "viewer"]}
    render={guardProps =&amp;gt; (
     &amp;lt;GenericComponent greet="user" {...guardProps} {...props} /&amp;gt;
   )}/&amp;gt;
 )}/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The GenericComponent is a simple hello world component and nothing else. This RouteGuard works perfectly with Lazy loading as we are just using the render props property of react-router-dom.&lt;/p&gt;

&lt;p&gt;The advantage of this approach is we have full access to router props &amp;amp; routeGuard props.&lt;/p&gt;

&lt;p&gt;Testing is also pretty clean for these Route Guards. As it is not possible to see the test tab in the embedded version of CodeSandbox you can click on this &lt;a href="https://codesandbox.io/s/objective-jennings-hlzf0?from-embed"&gt;https://codesandbox.io/s/objective-jennings-hlzf0?from-embed&lt;/a&gt; &amp;amp; then click on Open Sandbox on the bottom right corner to get a clearer picture.&lt;/p&gt;

&lt;p&gt;To check for the test cases click on the Test tab. (I know CodeSandbox is an awesome tool &amp;amp; everyone knows it :) )&lt;/p&gt;

&lt;p&gt;I have added comments in test cases &amp;amp; code for more clarity.&lt;/p&gt;

&lt;p&gt;Let me know your views in comments :)&lt;/p&gt;

</description>
      <category>react</category>
      <category>routeguards</category>
      <category>webdev</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
