<?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: Vignesh Pugazhendhi</title>
    <description>The latest articles on DEV Community by Vignesh Pugazhendhi (@vignesh_pugaz).</description>
    <link>https://dev.to/vignesh_pugaz</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%2F587221%2F32ecbe08-7ba5-4944-a081-fdd5ca1158aa.jpg</url>
      <title>DEV Community: Vignesh Pugazhendhi</title>
      <link>https://dev.to/vignesh_pugaz</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vignesh_pugaz"/>
    <language>en</language>
    <item>
      <title>Nestjs Series- Interceptors</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Mon, 31 Jan 2022 20:30:19 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/nestjs-series-interceptors-56o1</link>
      <guid>https://dev.to/vignesh_pugaz/nestjs-series-interceptors-56o1</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;Interceptors are classes decorated with @Injectable() decorator. The core concept of interceptors is based on Aspect Oriented Programming (AOP) paradigm. AOP is a programming paradigm to that aims to increase the modularity by allowing the separation of cross-cutting concerns.&lt;/p&gt;

&lt;p&gt;Interceptors are useful in the following scenarios:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;to bind some logic before a method handler is called&lt;/li&gt;
&lt;li&gt;to bind some logic after a method handler returns a response&lt;/li&gt;
&lt;li&gt;transform the exception thrown from a handler&lt;/li&gt;
&lt;li&gt;extend the basic function behaviour&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each interceptor class has to implement the NestInterceptor interface and thus have to satisfy all the method contracts.&lt;br&gt;
intercept() is such a method, taking 2 arguments. First argument is ExecutionContext, which we have already discussed in nestjs pipes and guards. ExecutionContext inherits the ArgumentsHost which is a wrapper around the arguments that have been passed to the handler. By inheriting the ArgumentsHost, it has several methods to provide details about the current execution context. The second argument to intercept() is of type CallHandler. CallHandler inherits the handle() method which is used to call the route handler method at any point of the execution. This is called the Pointcut, where in additional or transformed information is being passed to the route handler method.&lt;/p&gt;

&lt;p&gt;This means that the interceptor kind of wraps the request/response stream and thus can manipulate some logic before and after the route handler method calls. The handle() method returns an Observable, so we can use operators from rxjs to collect the response stream.&lt;/p&gt;

&lt;p&gt;The below code snippet is taken from the official nestjs docs to cover the basic understanding of interceptors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;CallHandler&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;Module&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;NestInterceptor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;UseInterceptors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;tap&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs/operators&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;LoggingInterceptor&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;NestInterceptor&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;intercept&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;CallHandler&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Before...&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;now&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;
      &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
      &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;tap&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`After...&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nx"&gt;now&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;)));&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Following code snippet is used to get the request object and perform some operations on it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;CallHandler&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;NestInterceptor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;BadRequestException&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;tap&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs/operators&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;DemoInterceptor&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;NestInterceptor&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;intercept&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;CallHandler&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;ctx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;switchToHttp&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;requestBody&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;ctx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;getRequest&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="nl"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;requestBody&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;length&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;BadRequestException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;name should be atleast 8 characters long&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;requestBody&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;requestBody&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;
      &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
      &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;tap&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;response from the method handler&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)));&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Above code is very obvious. tap() operator of rxjs library is used to execute an anonymous function once the entire response stream is captured from the method handler().&lt;/p&gt;

&lt;h1&gt;
  
  
  Binding Interceptors
&lt;/h1&gt;

&lt;p&gt;As with Guards and Pipes, Interceptors can be binded at one of the following three levels:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;at method handler level&lt;/li&gt;
&lt;li&gt;at module level&lt;/li&gt;
&lt;li&gt;at global level&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All you have to do is to decorator the levels with @UseInterceptors() decorator and pass on the Interceptor class or an instance of it as shown in the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Controller&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;user&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;UserController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;readonly&lt;/span&gt; &lt;span class="nx"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UserService&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;demoInterceptor&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;UseInterceptors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;DemoInterceptor&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
  &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;demoInterceptor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Body&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="nx"&gt;userDto&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nl"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createUser&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userDto&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At the global level:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;NestFactory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;AppModule&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;useGlobalInterceptors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;LoggingInterceptor&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And at the module level:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Module&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;APP_INTERCEPTOR&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Module&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;providers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;provide&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;APP_INTERCEPTOR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;useClass&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;LoggingInterceptor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;AppModule&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Interceptors can be used to timeout a request handler manually. When your endpoint doesn't return anything after a period of time, you want to terminate with an error response. The following construction enables this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;mport&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;NestInterceptor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;CallHandler&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;RequestTimeoutException&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;throwError&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;TimeoutError&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;catchError&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;timeout&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs/operators&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;TimeoutInterceptor&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;NestInterceptor&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;intercept&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;CallHandler&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nx"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
      &lt;span class="nx"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
      &lt;span class="nx"&gt;catchError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nx"&gt;TimeoutError&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;throwError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;RequestTimeoutException&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;throwError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="p"&gt;}),&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>nestjs</category>
      <category>javascript</category>
      <category>backenddev</category>
    </item>
    <item>
      <title>Nestjs Series- Guards</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Fri, 17 Dec 2021 18:51:28 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/nestjs-series-guards-4pn7</link>
      <guid>https://dev.to/vignesh_pugaz/nestjs-series-guards-4pn7</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;Guards! As the name suggests,it guards something from being accessible without permissions. Guards are a common concept in most backend frameworks,be it provided by the underlying framework or custom coded by the developer. Nestjs makes it simple for us to protect and safe guard apis from unauthorized or unauthenticated users.&lt;/p&gt;

&lt;p&gt;Like pipes and filters, guards in nestjs are decorated with @Injectable() decorator.Every guard you use must implement the CanActivate interface. The CanActivate interface properties make it easy developers to custom code their own guard logic.&lt;/p&gt;

&lt;p&gt;Let's understand the difference between a middleware and a guard to protect routes. A middleware is completely unaware of what is to be executed after it. A guard on the other hand has access to the &lt;code&gt;ExecutionContext&lt;/code&gt; instance and thus knows what is to be executed exactly after it.They are much like filters and pipes and can interpose the correct logic at the correct time in a Request-Response cycle.This property proves that a middleware is dumb.&lt;/p&gt;

&lt;p&gt;Guards are executed after each middleware and before and pipes or interceptors.&lt;/p&gt;

&lt;p&gt;Let's understand whatever is said with an example (the below code snippet is taken from nestjs official docs):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;AuthGuard&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanActivate&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nx"&gt;canActivate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;|&lt;/span&gt;&lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;switchToHttpRequest&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nx"&gt;getRequest&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
   &lt;span class="c1"&gt;//code to validate the request object for roles and &lt;/span&gt;
   &lt;span class="c1"&gt;//restrictions&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Going through the snippet, most of you must have understood the use of ExecutioContext.But what if one is wants to get the websocket connection context or a gql execution context. ExecutionContext covers all of them. All you need to do is switch to the appropriate context of your need and manipulate the logic. The ExecutionContext class extends the ArgumentsHost, providing you with the right methods to switch between the contexts. You can checkout the official docs as per your needs as this is out of the scope of this article.&lt;/p&gt;

&lt;p&gt;Let's talk about binding these guards now. As with pipes, filters and interceptors, guards can be controller-scoped,method-scoped or globally-scoped.Below we use a guard at the controller-scope level using @UseGuards() decorator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Controller&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;pokemons&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;UseGuards&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;AuthGuard&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;PokemonController&lt;/span&gt;&lt;span class="p"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have passed the class name of the Guard to the decorator. You can even pass and instance to the Guard or even a list of instances or types.&lt;/p&gt;

&lt;h1&gt;
  
  
  Setting up roles
&lt;/h1&gt;

&lt;p&gt;Roles are a way to tell the controller methods to allow the request-response cycle to complete.If a particular role is not authorized to access an endpoint, the request-response cycle is ended here by returning an unauthorized error message, typically with a 401 HTTP statuscode. Our guards are very smart but they do not know which roles are allowed for which endpoints.This is where custom metadata comes into play. With custom metadata, we can segregate endpoints based on the roles as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/updateAccess&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;SetMetadata&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;roles&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;superadmin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;updateReadWriteAccessofUser&lt;/span&gt;&lt;span class="p"&gt;(@&lt;/span&gt;&lt;span class="nd"&gt;Body&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="nx"&gt;inputDto&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;adminService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;inputDto&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have assigned the roles to the updateReadWriteAccessOfUser method. Only the user with "admin" and "superadmin" roles can access this endpoint "/updateAccess".While this is enough for this concept to be understood, it is not a good practice to assign roles directly on the controller methods. Instead we can code our own decorator for this and use it. We code this such that it follows DRY solid principle.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;SetMetadata&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;Roles&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(...&lt;/span&gt;&lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[])&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;SetMetadata&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;roles&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Now you can reuse this decorator whereever needed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/updateAccess&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Roles&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;superadmin&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;updateReadWriteAccessofUser&lt;/span&gt;&lt;span class="p"&gt;(@&lt;/span&gt;&lt;span class="nd"&gt;Body&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="nx"&gt;inputDto&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;adminService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;inputDto&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we combine the concepts of roles and guards to protect our endpoint from unauthorized requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;CanActivate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Reflector&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;RolesGuard&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanActivate&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;reflector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Reflector&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="nx"&gt;canActivate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ExecutionContext&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;roles&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;reflector&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;roles&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;getHandler&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;switchToHttp&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nx"&gt;getRequest&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;verifyRoles&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;Roles&lt;/span&gt;&lt;span class="p"&gt;(...&lt;/span&gt;&lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[])&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;applyDecorators&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nx"&gt;SetMetadata&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;roles&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nx"&gt;UseGuards&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;RolesGuard&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


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

&lt;/div&gt;



&lt;p&gt;The Reflector helper class is provided by the nestjs framework to access the controller method's roles. We verify the roles the current request's roles and return a boolean based on the verification. In the second code snippet, we make use of this RolesGuard as a paramter to the applyDecorators. The applyDecorators method combines multiple decorators and executes them.&lt;/p&gt;

&lt;p&gt;Any exception thrown by a guard will be handled by the exceptions layer (global exceptions filter and any exceptions filters that are applied to the current context).&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>NestJS Series - Pipes</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Sat, 20 Nov 2021 12:55:35 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/nestjs-series-pipes-1jg3</link>
      <guid>https://dev.to/vignesh_pugaz/nestjs-series-pipes-1jg3</guid>
      <description>&lt;p&gt;Most backend developers can relate the pain of validating and transforming the data passed in the request body or in params or in queries. Most of us either code custom validation and transformation methods or use any open source library. Nestjs supports both through pipes. Pipes in nestjs like any other backend framework have two typical use cases: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. transformation&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;2. validation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In transformation, the input data is transformed into a desired form, eg: transforming every string in an array to lowercase or uppercase.&lt;/p&gt;

&lt;p&gt;In validation, we validate the input data and simply pass it unchanged if the data is correct and throw an error if the data is incorrect.&lt;/p&gt;

&lt;p&gt;Pipes handle both the cases by operating on the arguments being passed to a route controller or a resolver.Nest interposes pipes before any controlled or a resolver method is executed. Pipes receive the arguments passed to the controller and either of validation or transformation code is run on the arguments to decide whether to throw an exception or to transform the data or to pass it unchanged back to the controller's context.&lt;/p&gt;

&lt;p&gt;NodeJS developers might worry about exception handling but nestjs takes care of exceptions thrown by pipes. Pipes run only inside the exception zone and all the error handing stuff is taken care by the underlying framework.&lt;/p&gt;

&lt;p&gt;Nestjs comes with 8 built in pipes out of which 6 are transformation pipes and 1 is a validation pipe.There is an extra pipe which sets a default value, known as the DefaultValuePipe.Enough of the theory, let's jump into the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;:_id&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;findUserById&lt;/span&gt;&lt;span class="p"&gt;(@&lt;/span&gt;

&lt;span class="nx"&gt;Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;_id&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;ParseIntPipe&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;findById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;ParseIntPipe transforms the param _id from a string to a number. Notice how we have binded the pipe in the &lt;a class="mentioned-user" href="https://dev.to/param"&gt;@param&lt;/a&gt; decorator.You can also instantiate the pipe yourself and change it's behaviour if needed or let nestjs do it for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;:_id&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;findUserById&lt;/span&gt;&lt;span class="p"&gt;(@&lt;/span&gt;&lt;span class="nd"&gt;Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;_id&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;ParseIntPipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="nx"&gt;errorHttpStatusCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;HttpStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;NOT_ACCEPTABLE&lt;/span&gt; &lt;span class="p"&gt;}))&lt;/span&gt; &lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;findById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;As long as your need is minute, you can use the nestjs's built-in transformation pipes.But what if your pipes need to transform or validate based on your project's use cases. Well nest allows us to build our own custom pipes. All we have to do is to implement the PipeTransform class and fulfill the contract of using it's method, transform. This is shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;PipeTransform&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;ArgumentMetaData&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;CustomPipeTransformation&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;PipeTransform&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;ArgumentMetaData&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here value is the data you pass in the request body or as params or as queries. metadata of type ArgumentMetaData contains the metadata associated with the data you pass.&lt;/p&gt;

&lt;p&gt;This is an object with 3 keys, data,type and metatype.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kr"&gt;interface&lt;/span&gt; &lt;span class="nx"&gt;ArgumentMetadata&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;body&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;query&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;param&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;custom&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;metatype&lt;/span&gt;&lt;span class="p"&gt;?:&lt;/span&gt; &lt;span class="nx"&gt;Type&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;unknown&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;?:&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;type denotes how you pass the data, either in body or in params or in queries.&lt;br&gt;
metatype is the type of the data you send, eg:string&lt;br&gt;
data is the name you pass to the decorator. eg: @Body('email')&lt;/p&gt;

&lt;p&gt;These 3 keys and the value argument can enough to transform or validate your data. Following code snippet converts an argument of array of strings to array of uppercase strings.That is each element in the array is transformed to it's uppercase version.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;PipeTransform&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;ArgumentMetadata&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;BadRequestException&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;joi&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;PipeTransformCustom&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;PipeTransform&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;metatype&lt;/span&gt; &lt;span class="p"&gt;}:&lt;/span&gt; &lt;span class="nx"&gt;ArgumentMetadata&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;isTypeAcceptable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;metatype&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;===&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;body&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[]).&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="na"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;val&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;toLocaleUpperCase&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;BadRequestException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
      &lt;span class="s2"&gt;`Argument expected should be an array of strings!`&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="nx"&gt;isTypeAcceptable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;function&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;Array&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;isArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;every&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;val&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note how we destructure the metadata and make use of it's keys. First the metatype is being checked if it is of type "function" and value being checked if it is an array. Once this is done, we check if every element in the array is of type "string". Once both the cases pass, we convert every element of the array to it's locale uppercase. This example is a combination of both validation and transformation.&lt;/p&gt;

&lt;p&gt;To make use of this pipe,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Controller&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;convert-upper-case&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;UsePipes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;PipeTransformCustom&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;convertToUppercase&lt;/span&gt;&lt;span class="p"&gt;(@&lt;/span&gt;&lt;span class="nd"&gt;Body&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;array&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[]):&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There's another type of validation known as schema-based validation which validates your request body data against a schema. By schema I don't mean an actual DB schema,it may be an interface or class.&lt;/p&gt;

&lt;p&gt;This is explained in the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;UserSignupDto&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nl"&gt;username&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nl"&gt;phone&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nl"&gt;above18&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to validate any incoming data against this schema, we have two options: either we can do it manually as explained above or we can make use of libraries. The Joi library allows you to create schemas in a straightforward way, with a readable API&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;npm&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="nx"&gt;joi&lt;/span&gt; &lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="nx"&gt;save&lt;/span&gt;
&lt;span class="nx"&gt;npm&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;types&lt;/span&gt;&lt;span class="sr"&gt;/joi --save-de&lt;/span&gt;&lt;span class="err"&gt;v
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We install types support for Joi as a dev dependency.Now to utilize this lib,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;PipeTransform&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;ArgumentMetadata&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;BadRequestException&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;ObjectSchema&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;joi&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;JoiValidationPipe&lt;/span&gt; &lt;span class="kr"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;PipeTransform&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;schema&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ObjectSchema&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="nx"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ArgumentMetadata&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;BadRequestException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Validation failed&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Post&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;UsePipes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;JoiValidationPipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;UserSignupDto&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nx"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(@&lt;/span&gt;&lt;span class="nd"&gt;Body&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="nx"&gt;createUserDto&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UsersignupDto&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;createUserDto&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here we make use of Joi lib to validate the data against the UserSignupDto. The code is pretty starightforward and can be understood easily. That's how  Joi makes validation look easy.&lt;/p&gt;

&lt;p&gt;An added advantage of nest is it works well with class-validator library. This powerful library allows you to use decorator-based validation. Decorator-based validation is extremely powerful, especially when combined with Nest's Pipe capabilities since we have access to the metatype of the processed property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;npm&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="nx"&gt;save&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;validator&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;transformer&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once installed we can add decorators to our UserSignupDto schema.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;IsString&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;IsBoolean&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;IsNumber&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;class-validator&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;UserSignupDto&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;IsString&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;IsString&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nx"&gt;username&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;IsNumber&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nx"&gt;phone&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;IsBoolean&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nx"&gt;above18&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;If needed, you can read about class-validator here &lt;a href="https://github.com/typestack/class-validator#usage"&gt;class-validator&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can also bind pipes at different contexts of the code- be it an controller level, module level or at global level.&lt;/p&gt;

&lt;p&gt;I'm attaching the code snippets from official docs for module and global level. Please refer to the docs if an in-depth knowledge is needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Module level&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Module&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/common&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;APP_PIPE&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@nestjs/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Module&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;providers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;provide&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;APP_PIPE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;useClass&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ValidationPipe&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;AppModule&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Global Level&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;bootstrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;NestFactory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;AppModule&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;useGlobalPipes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;ValidationPipe&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nx"&gt;bootstrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Pipes to some extent make the code less vulnerable to production bugs.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>nestjs</category>
    </item>
    <item>
      <title>Conditionally render your DOM in ReactJS</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Fri, 05 Nov 2021 21:24:56 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/conditionally-render-your-dom-in-reactjs-ca3</link>
      <guid>https://dev.to/vignesh_pugaz/conditionally-render-your-dom-in-reactjs-ca3</guid>
      <description>&lt;p&gt;Most single page applications are dynamic and change content frequently depending upon the end user's actions.One of the features of reactjs that allows this is called conditional rendering. Reactjs allows us to render a fragment of DOM conditionally. This is very much similar to conditional statements in any programming language.&lt;/p&gt;

&lt;p&gt;Conditions can be applied to a number of scenarios. The below are not limited to but are some cases where condtional rendering can be used:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;render data of an API call&lt;/li&gt;
&lt;li&gt;show or hide elements based on user's actions such as a 
button click or a change in the value of a dropdown&lt;/li&gt;
&lt;li&gt;to toggle application functionality&lt;/li&gt;
&lt;li&gt;hide or display elements based on roles (authorization)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Below are some of the ways to condtionally render a DOM fragment:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Using If...Else&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This can be opted if and only if the condition holds two values.Following code snippet explains the use of If..Else conditional statement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const DISCOUNTS=["offer',"promocode"];
export default function App({...props})=&amp;gt;{
   const [discountSelected,setDiscountSelected]=useState(DISCOUNTS[0]);
   function renderForm(){
      if(discountSelected===DISCOUNTS[0]){
         &amp;lt;form&amp;gt;
           &amp;lt;label&amp;gt;Offer Name&amp;lt;/label&amp;gt;
           &amp;lt;input type="text" /&amp;gt;
         &amp;lt;/form&amp;gt;
      }else{
         &amp;lt;form&amp;gt;
           &amp;lt;label&amp;gt;Promocode Name&amp;lt;/label&amp;gt;
           &amp;lt;input type="text" /&amp;gt;
         &amp;lt;/form&amp;gt;
      }
   }
   function handleDiscountChange(){
     if(discountSelected===DISCOUNTS[0]){
        setDiscountSelected(DISCOUNTS[1]);
     }else{
        setDiscountSelected(DISCOUNTS[0])
     }
   }
   return (
     &amp;lt;div&amp;gt;
        &amp;lt;button onClick={handleDiscountChange}&amp;gt;Change Discount Type&amp;lt;/button&amp;gt;
        {renderForm()}
     &amp;lt;/div&amp;gt;
   );
}

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

&lt;/div&gt;



&lt;p&gt;We could have conditionally rendered the component inside the return statement but it is always advisable to keep your code clean.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Using Switch Statement&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The above result could be achieved using a simple switch statement but always use a switch statement only when you want to render DOM based on many different values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AuthButton = props =&amp;gt; {
  let { isLoggedIn } = props;

  switch (isLoggedIn) {
    case true:
      return &amp;lt;button&amp;gt;Logout&amp;lt;/button&amp;gt;;
      break;
    case false:
      return &amp;lt;button&amp;gt;Login&amp;lt;/button&amp;gt;;
      break;
    default:
      return null;
  }
};

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Using variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Variables can be used to render DOM conditionally. Initialize a variable and set it value to some snippet of DOM based on the conditions.Below code fragment explains the use case&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App(){
    let { isLoggedIn } = this.state;
    let AuthButton;

    if (isLoggedIn) {
      AuthButton = &amp;lt;button&amp;gt;Logout&amp;lt;/button&amp;gt;;
    } else {
      AuthButton = &amp;lt;button&amp;gt;Login&amp;lt;/button&amp;gt;;
    }

    return (
      &amp;lt;div className="App"&amp;gt;
        &amp;lt;h1&amp;gt;
           Conditional rendering using variables
        &amp;lt;/h1&amp;gt;
        {AuthButton}
      &amp;lt;/div&amp;gt;
    );

}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Using ternary operator&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ternary operator is similar to If...Else statement expect for the fact that the code is clean and as small as possible.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App({...props}){
  let { isLoggedIn } = this.state;

    return (
      &amp;lt;div className="App"&amp;gt;
        &amp;lt;h1&amp;gt;
          This is a Demo showing several ways to implement Conditional Rendering in React.
        &amp;lt;/h1&amp;gt;
        {isLoggedIn ? &amp;lt;button&amp;gt;Logout&amp;lt;/button&amp;gt; : &amp;lt;button&amp;gt;Login&amp;lt;/button&amp;gt;}
      &amp;lt;/div&amp;gt;
    );
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Using Short Circuit Evaluation&lt;/strong&gt;&lt;br&gt;
This can be used with a single condition or a combination of conditions. Below code fragment demonstrates the use case:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const App=(props)=&amp;gt;{
  let { isLoggedIn } = this.state;

    return (
      &amp;lt;div className="App"&amp;gt;
        &amp;lt;h1&amp;gt;
          This is a Demo showing several ways to implement Conditional Rendering in React.
        &amp;lt;/h1&amp;gt;
        {isLoggedIn &amp;amp;&amp;amp; &amp;lt;button&amp;gt;Logout&amp;lt;/button&amp;gt;}
      &amp;lt;/div&amp;gt;
    );
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. IIFEs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Immediately invoked functions or IIFEs can be used to execute a function code block with any of the above use cases:&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App(props){
  return (
      &amp;lt;div className="App"&amp;gt;
        &amp;lt;h1&amp;gt;
          This is a Demo showing several ways to implement Conditional Rendering in React.
        &amp;lt;/h1&amp;gt;
        {(function() {
          if (isLoggedIn) {
            return &amp;lt;button&amp;gt;Logout&amp;lt;/button&amp;gt;;
          } else {
            return &amp;lt;button&amp;gt;Login&amp;lt;/button&amp;gt;;
          }
        })()}
      &amp;lt;/div&amp;gt;
    );
}

``




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

&lt;/div&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Unit testing a react component which uses context API</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Tue, 31 Aug 2021 17:55:39 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/unit-testing-a-react-component-which-uses-context-api-3nen</link>
      <guid>https://dev.to/vignesh_pugaz/unit-testing-a-react-component-which-uses-context-api-3nen</guid>
      <description>&lt;h1&gt;
  
  
  Unit Testing
&lt;/h1&gt;

&lt;p&gt;In programming, unit testing is the method to test a single unit of code. A single unit of code may be one or more program modules combined together or the smallest unit of working code that cannot be divided further, by doing so the unit on the whole is not functional as expected.If you are familiar with reactjs testing libraries like jest and enzyme, jasmine or react-testing-library, you must have tested individual components on the top level by shallow rendering. Shallow rendering renders a particular component without rendering it's children for it to be tested.Here we will be learning how to unit test a react component using context API with the help of enzyme testing utility.&lt;/p&gt;

&lt;h1&gt;
  
  
  Enzyme
&lt;/h1&gt;

&lt;p&gt;Enzyme is not a testing library.It is more of a testing utility which lets you manipulate,traverse,interact with the DOM elements. Enzyme can be used with jest or karma or mocha depending upon the need.&lt;/p&gt;

&lt;h1&gt;
  
  
  Context API
&lt;/h1&gt;

&lt;p&gt;Context API by reactjs provides a way to pass down the data to the components without having to actually pass the data as props at each level. For example, consider component A having 3 nested children B,C and D.If A has to pass some values to D,instead of prop drilling the values, one can wrap the component D as a consumer of the context and A as a provider.&lt;br&gt;
Context API might sound similar to react-redux architecture but it is completely different from it.&lt;br&gt;
For those who do not have an experience working with context API, you can go through the reactjs documentation for better understanding&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;unit testing context api&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider the following piece of code to setup a context:&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';

export default React.createContext("en")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's call this file languageContext.js. Now since the context is now defined, we can wrap our root component as the provider.&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, { useEffect, useState } from "react";
import "./App.css";
import GuessedWord from "./GuessedWord/GuessedWord";
import LanguagePicker from "./GuessedWord/LanguagePicker";
import languageContext from "./languageContext";

/**
 * @function reducer to update state automatically when dispatch is called
 * @param state {object} previous state
 * @param action {object} type and payload properties
 * @return {object} new state
 */

const reducer = (state, action) =&amp;gt; {
  switch (action.type) {
    case "setSecretWord":
      return { ...state, secretWord: action.payload };
    case "setLanguage":
      return { ...state, language: action.payload };
    default:
      throw new Error(`Invalid action type ${action.type}`);
  }
};

function App(props) {
  //const [secretWord,setSecretWord]=useState('');

  const [state, dispatch] = React.useReducer(reducer, {
    secretWord: "",
    language: "en",
  });

  const success = false;
  const guessedWords = [];

  const setSecretWord = (secretWord) =&amp;gt; {
    dispatch({ type: "setSecretWord", payload: secretWord });
  };

  const setLanguage = (lang) =&amp;gt; {
    dispatch({ type: "setLanguage", payload: lang });
  };

  useEffect(() =&amp;gt; {
    getSecretWord(setSecretWord);
  }, []);

  let content;
  if (!state.secretWord.length) content = &amp;lt;div data-test="spinner" /&amp;gt;;
  else
    content = (
      &amp;lt;&amp;gt;
        &amp;lt;h1&amp;gt;Jotto&amp;lt;/h1&amp;gt;
        &amp;lt;languageContext.Provider value={state.language}&amp;gt;
          &amp;lt;LanguagePicker setLanguage={setLanguage} /&amp;gt;
          &amp;lt;GuessedWord guessedWords={guessedWords} /&amp;gt;
        &amp;lt;/languageContext.Provider&amp;gt;
      &amp;lt;/&amp;gt;
    );

  return &amp;lt;div data-test="component-app"&amp;gt;{content}&amp;lt;/div&amp;gt;;
}

export default App;

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

&lt;/div&gt;



&lt;p&gt;The LanguagePicker component is as follows:&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 propTypes from "prop-types";

function LanguagePicker({setLanguage}) {
  const languages = [
    { code: "en", symbol: "🇺🇸" },
    { code: "ar", symbol: "🇦🇪" },
  ];
  const languageIcons = languages.map((lang) =&amp;gt; {
    return (
      &amp;lt;span
        key={lang.code}
        data-test="language-icon"
        onClick={() =&amp;gt; setLanguage(lang.code)}
      &amp;gt;
        {lang.symbol}
      &amp;lt;/span&amp;gt;
    );
  });
  return &amp;lt;div data-test="component-language-picker"&amp;gt;{languageIcons}&amp;lt;/div&amp;gt;;
}

LanguagePicker.propTypes = {
  setLanguage: propTypes.func.isRequired,
};

export default LanguagePicker;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The LanguagePicker component allows us to select a language of preference which we store in a local state of our root-level component. We wrap the App.js,our root-level-component as a Context Provider. This is done so that the root-level component acts a data provider to the child components. We pass the data as a "value" prop. So each of the child components now has access to this value prop as each of them act as a consumer.&lt;/p&gt;

&lt;p&gt;The GuessedWords component is as follows:&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 PropTypes from "prop-types";

//services and helpers
import languageContext from "../context/languageContext";
import {getStringsByLanguage} from './strings';

function GuessedWord({ guessedWords }) {
  const language=React.useContext(languageContext);
  if (!guessedWords.length)
    return (
      &amp;lt;div data-test="guessed-word-component"&amp;gt;
        &amp;lt;span data-test="instructions"&amp;gt;{getStringsByLanguage(language,"guessPrompt")}&amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  return (
    &amp;lt;div data-test="guessed-word-component"&amp;gt;
      &amp;lt;table data-test="table"&amp;gt;
        &amp;lt;thead&amp;gt;
          &amp;lt;tr&amp;gt;
            &amp;lt;th&amp;gt;GuessedWord&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Match Count&amp;lt;/th&amp;gt;
          &amp;lt;/tr&amp;gt;
        &amp;lt;/thead&amp;gt;
        &amp;lt;tbody&amp;gt;
          {guessedWords.map((guess, index) =&amp;gt; (
            &amp;lt;tr key={index} data-test="rows"&amp;gt;
              &amp;lt;th&amp;gt;{guess.guessedWord}&amp;lt;/th&amp;gt;
              &amp;lt;th&amp;gt;{guess.match}&amp;lt;/th&amp;gt;
            &amp;lt;/tr&amp;gt;
          ))}
        &amp;lt;/tbody&amp;gt;
      &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

GuessedWord.propTypes = {
  guessedWords: PropTypes.arrayOf(
    PropTypes.shape({
      guessedWord: PropTypes.string.isRequired,
      match: PropTypes.number.isRequired,
    })
  ).isRequired,
};

export default GuessedWord;

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

&lt;/div&gt;



&lt;p&gt;We make use of React.useContext() hook to access the "value" prop of the parent component's provider wrapper. We pass the languageContext as an argument to the hook.&lt;br&gt;
The function getStringsByLanguage returns the localized string based on the language chosen. Now our task is to unit test this component. We test two scenarios here. If the language chosen is "en", we will return "Try to guess the secret word". If the language chosen is "ar" , we return "حاول تخمين الكلمة السرية". The code for the unit test file is as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { shallow } from "enzyme";
import checkPropTypes from "check-prop-types";
import GuessedWord from "./GuessedWord";


const defaultProps = {
  guessedWords: [{ guessedWord: "train", match: 3 }],
};

const setup = (props = defaultProps) =&amp;gt; {
  return shallow(&amp;lt;GuessedWord {...props} /&amp;gt;);
};
describe("language picker scenarios", () =&amp;gt; {
  test("should prompt the guess instruction in english", () =&amp;gt; {
    const wrapper = setup({ guessedWords: [] });
    const guessInstruction = wrapper.find(`[data-test="instructions"]`);
    expect(guessInstruction.text()).toBe("Try to guess the secret word");
  });
  test("should prompt the guess instruction in arabic", () =&amp;gt; {
    const originalUseContext = React.useContext;
    const mockReactUseContext = jest.fn().mockReturnValue("ar");
    React.useContext = mockReactUseContext;
    const wrapper = setup({ guessedWords: [] });
    const guessInstruction =  wrapper.find(`[data-test="instructions"]`);
expect(guessInstruction.text()).toBe("حاول تخمين الكلمة السرية");
React.useContext=originalUseContext;
  });
});

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

&lt;/div&gt;



&lt;p&gt;We shallow render the GuessedWords component. We know that the default language is "en" in the context provider.So the first test case should be obvious to you. In the second test case, we mock the original React.useContext() hook and we set the language as "ar"; Now since the language is set to arabic and the GuessedWords component is shallow rendered, our assertion should be the text displayed in arabic.It is always a good practice to mock your functions or hooks in your component and restore them after each assertion.This is done so that the original definition of your function or hook is restored for all other test cases in your test suite which are using them.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>testing</category>
    </item>
    <item>
      <title>GraphQL-update cache and network fetch policies</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Thu, 08 Jul 2021 17:24:14 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/graphql-update-cache-and-network-fetch-policies-103m</link>
      <guid>https://dev.to/vignesh_pugaz/graphql-update-cache-and-network-fetch-policies-103m</guid>
      <description>&lt;p&gt;I expect the readers to have basic graphql knowledge, how to setup a graphql server, how to mutate and query from a reactjs application using a gql library like apollo-client. We will move ahead with react apollo client library. Apollo client is a declarative data fetching and management library for your reactjs applications wherein different states of fetching data from an API or from a remote server can be managed. Traditional ways of doing the same thing can be achieved using RESTful webservice. In RESTful webservice, we expect the webAPI XMLHttpRequest to listen to various events based on which we can alter the UI. For example, when a XMLHttpRequest is made, we can show up a loader to indicate the request has been made and is been processed by the server.Once we receive the data from the server, we can render the result instead of showing up a loader. There are many libraries which can take care of all the events occuring in a promisified way like axios,superagent or the fetch api itself. So if all these events can be managed by such good well coded libraries, why do we opt for graphql?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages of GQL over RESTful webservice:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Instead of working with fixed rigid server-defined endpoints,you can make a single query request to a gql server demanding only those parts of data you need.&lt;/li&gt;
&lt;li&gt;GQL reduces the number of endpoints your application makes request to. A single resolver can be used to handle multiple request formats&lt;/li&gt;
&lt;li&gt;In REST, each request calls exactly one request handler whereas in gql,one query may call many resolvers to construct a nested response.&lt;/li&gt;
&lt;li&gt;In REST, you define the structure of the response, whereas in graphql  the shape of the response is built up by the GraphQL execution library to match the shape of the query.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Understand how to update cache&lt;/strong&gt;&lt;br&gt;
In order to implement caching in GQL, one needs to figure it out which one of the following scenarios covers your requirement:&lt;/p&gt;

&lt;p&gt;Consider the following code snippet of a gql server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {ApolloServer,gql} from 'apollo-server';

const typeDefs=gql`
type Book{
  id:ID!
  title:String!
  author:String!
}
type Mutation{
  createBook(title:String!,author:String!):Book!
  updateBook(id:String!,title:String!,author:String!):Book!
  deleteBook(id:String!):Boolean!
}
type Query{
  books:[Book!]!
  searchBook(searchKey:String!):[Book!]!
}
`;

const resolvers={
  Mutation:{
    createBook:(_,{title,author})=&amp;gt;{
    const book={id:`${books.length+1}`,title,author}
    books.push(book);
    return book;
  },
  updateBook:(_,Book){
    books=books.map(x=&amp;gt;x.id===book.id?book:x)
    return book;
  },
  deleteBook:(_,{id}){
    books=books.filter(x=&amp;gt;x.id!==id);
    return true;
  }
},
Query:{
  books:()=&amp;gt;books,
  searchBooks:(_,{searchKey})=&amp;gt;{
    const searchedBooks=books.filter((book)=&amp;gt;{
    return book.title.includes(searchey)
    }
    return searchBooks;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a book repository backend application where you can create,read,update and delete a book.Also searchBooks query is used to search books from the repository based on a searchKey.&lt;/p&gt;

&lt;p&gt;Now what we want is to show the user a created book without he/she refreshing a page, a delete book should be removed from UI without refreshing a page, a book should be update and again without refreshing the page.This is where caching comes into play. What gql does is it updates the cache based on a unique and __typename returned by the gql server.For eg, when we create a book, the response would be :&lt;/p&gt;

&lt;p&gt;{&lt;br&gt;
id,&lt;br&gt;
title,&lt;br&gt;
author&lt;br&gt;
__typename:Book&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Your web browser cache is a lookup table or a hashtable to be precise.GQL combines id and __typename to assign a key as a hash and the response as it's corresponding value.This key-value pair is responsible for fetching data from your browser's cache in a constant time O(1) which we will be looking at once we understand network fetch-policies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 1 : creating a book&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This case has two sub cases whereby you can update your UI without refreshing the page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; createBook({
      variables: {
        title: "Megastructures",
        author: "Discovery",
      },
      refetchQueries:[{query:Q_FETCH_BOOKS}]
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;createBook({
      variables: {
        title: "Malaysian Dreams",
        author: "travel and living",
      },
      update: (store, { data }) =&amp;gt; {            //data is response from api
        const bookData = store.readQuery({ query: Q_FETCH_BOOKS });
        store.writeQuery({
          query: Q_FETCH_BOOKS,
          data: {
            books: [...bookData.books, data.createBook],
          },
        });
      },
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;refetch is basically going to fetch the updated db and return it to the client once the mutation is completed whereas in the second case we manually update the cache.GQL makes use of the id and __typename of update the cache and UI automatically. A frontend developer need not do anything  else other than updating the cache the cache manually and the rest is taken care by the apollo-client. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 2 : update a book&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;updateBook({
      variables: {
        id: "1",
        title: "Banged up abroad",
        author: "National Geographic",
      },
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is very much similar to scenario 1, except for the fact that we do not need to update the cache manually.Apollo client will map the updated data to the hashtable based on the combination of id+__typename&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 3: Deleting a book&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Delete is similar to the subcase 2 of scenario 1. Send a mutation to the server, once it is confirmed that the book is deleted in the server, update the cache manually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 4: Searching a book&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [searchBook, { loading, data, error }] = useLazyQuery(Q_SEARCH_BOOKS, {
    onCompleted: (data) =&amp;gt; {
      console.log(" search books onCompleted", data);
    },
    fetchPolicy: "cache-and-network",
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Fetch Policies:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;cache-first&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;default policy&lt;/li&gt;
&lt;li&gt;cache is checked first. If requested data is present,the data is returned. Else network request is made to api &amp;amp; cache is updated&lt;/li&gt;
&lt;li&gt;Better option to update the cache&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;cache-and-network&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;cache is checked first. Regardless of whether data is found or not, a network request is made to get upto date data&lt;/li&gt;
&lt;li&gt;updates the cache wrt to network response&lt;/li&gt;
&lt;li&gt;can be useful when an operation is performed in one of the sub-component and you need updated data in it's sibling component.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;network-only&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;always makes a network request. Will update the cache for other queries&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;no-cache&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;similar to network-only. Does not update cache&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;cache-only&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;never makes a network request,always returns data from the cache.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>graphql</category>
    </item>
    <item>
      <title>Lazy Loading In ReactJS</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Mon, 29 Mar 2021 12:29:54 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/lazy-loading-in-reactjs-1jna</link>
      <guid>https://dev.to/vignesh_pugaz/lazy-loading-in-reactjs-1jna</guid>
      <description>&lt;p&gt;Ever worked with or tried to understand the concepts of a web bundler like webpack or browserify? We often split the source code and import the dependencies where ever required. What we work in, is a code splitted environment where we code UI and business logic into different components and import them at the required places. In a broad terminology, this is known as modular programming. If you try inspecting your UI in a developer's tool, you can see all the components are loaded at once. This is because all the dependencies are bundled together and imported as a single file. This is known as bundling.&lt;/p&gt;

&lt;p&gt;Now, as your app grows, your bundler will try to import all the dependencies including any third party packages and libraries installed, all at once. This might make your application to take an ample amount of time to load. Reactjs &amp;gt;=16.6 has introduced a common design pattern called &lt;code&gt;lazy loading&lt;/code&gt;, which defers the initialization of an object until the point in the code where it is really needed. This might sound analogous to promises in js, but trust me this is going to save millions for your company.&lt;/p&gt;

&lt;h1&gt;
  
  
  React.lazy
&lt;/h1&gt;

&lt;p&gt;lazy is a function to import your components dynamically. By dynamically, I mean the component is only loaded when it is needed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import someComponent from './someComponent';

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

&lt;/div&gt;



&lt;p&gt;The above code snippet might be bundled by your bundler as a normal dependency. What we might want could be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const someComponent=React.lazy(()=&amp;gt;import('./someComponent'));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is called dynamic importing. React.lazy() expects a promise. This promise resolves to a module. While this component is being loaded, you might need a fallback such as a loader.&lt;/p&gt;

&lt;p&gt;Wrap the imported component with &lt;code&gt;&amp;lt;Suspense&amp;gt;&amp;lt;/Suspense&amp;gt;&lt;/code&gt;. The  component takes a fallback prop. The fallback is rendered meanwhile the dynamic import is resolved into a module.&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 Loader from './loader';

const someComponent=React.lazy(()=&amp;gt;import('./someComponent'));
const otherComponent=React.lazy(()+.import('./otherComponent'));

export default ()=&amp;gt;{
return (
 &amp;lt;React.Suspense fallback={&amp;lt;Loader/&amp;gt;}&amp;gt;
   &amp;lt;someComponent/&amp;gt;
   &amp;lt;otherComponent/&amp;gt;
 &amp;lt;/React.Suspense&amp;gt;
);
}

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

&lt;/div&gt;



&lt;p&gt;Instead of wrapping a whole component with  component, you can wrap those sections of the component where lazy loading is to be applied. Adding further, there might a situation where a component may not be loaded due to technical issues such as a network error or gql error. In that case, global error handling can be done using ErrorBoundary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenarios where you may need lazy loading&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Routing : If your application is a SPA with multiple routes, you may need to load components only when they are routed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To improve you app performance : You may not want your customers to experience a poor UI/UX experience by loading all heavy components at once.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Assets : If your application contains media files such as images and audio files, for eg in a music player app, you may want to load assets only when the end user needs it.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Limitations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lazy loading feature is still not a usable feature is server-side rendered applications (SSR) . However, make use of reactjs provided Loadable components if needed.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
    </item>
    <item>
      <title>let or const or var? When to use what?</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Wed, 03 Mar 2021 19:14:20 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/let-or-const-or-var-when-to-use-what-57mh</link>
      <guid>https://dev.to/vignesh_pugaz/let-or-const-or-var-when-to-use-what-57mh</guid>
      <description>&lt;p&gt;Unlike most programming languages, javascript variables are declared with the var keyword. Before es6, var was much prevalent and was commonly used to declare and initialize variables. Javascript is a weird language. Expect the unexpected when working with js. So, what was the need of two new keywords when var does everything you need to declare and initialize variables. Well, there are three main issues to be looked upon next time you decide to use var.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scope&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Variables declared with var keyword can be either globally scoped or locally scoped(inside a function or a block of code).By globally scoped, I mean the variable is accessible throughout the document or in the whole window. Locally scoped variables are available only within the function body or block of code in which it is declared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var pokemon="pikachu";
function catchNewPokemon(){
  var newPokemon="charmendar";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, pokemon is globally scoped and newPokemon is locally scoped.&lt;br&gt;
newPokemon cannot be accessed outside the function. Doing so will throw a reference error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Redeclaration&lt;/strong&gt;&lt;br&gt;
A variable declared with var keyword can be redeclared within the same scope. Doing so might produce buggy codes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var pokemon="Bulbasaur";
var pokemon="Ivasaur";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's say you declare a variable pokemon in line 119 of your production code and again re-declare pokemon in line 556 unknowingly.&lt;br&gt;
The subsequent code after line 556, will be carrying a value you assigned to it in line 556.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hoisting&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;All variables declared with var are automatically hoisted to the top of their scopes. For example :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(pokemon)
var pokemon="pikachu"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;will throw no undefined variable error as pokemon is hoisted automatically to the top of it's scope.&lt;/p&gt;

&lt;p&gt;Now, to overcome the above issues, ECMAScript, an internationally recognized standard, has come up with two new keywords let and const.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;let&lt;/strong&gt;&lt;br&gt;
let is by default block scoped. Now matter how many times you declare the same variable in your code, the compiler won't throw an error unless the variables are in different scopes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pokemon="pikachu";
const catchPokemon=()=&amp;gt;{
   let pokemon="bulbasaur";
   console.log(pokemon)  //consoles bulbasaur
}
console.log(pokemon) //consoles pikachu
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, variable declared with let can only be updated and cannot be declared within the same scope.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let pokemon="pikachu";
let pokemon="raichu"; //error:Identifier pokemon has been already declared
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Like var, variables declared with let are hoisted to the top of their scopes. The only difference is, here they are not initialized as undefined. You will get a reference error if you try to use a variable before it is declared.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;const&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Identifiers declared with const are block scoped and cannot be updated once they are declared and initialized. Infact, declaration and initialization happens at the same time. You cannot declare a const and initialize it later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pokemon;
pokemon="pikachu"; //error: Uncaught SyntaxError: Missing initializer in const declaration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pokemon="squirtle";
pokemon="Blastoise"; //error: Identifier 'pokemon' has already been declared
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Try using let everywhere in the code whenever you declare a variable.&lt;br&gt;
Use const only if you need an identifier to carry a constant value throughout your code.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>es6andabove</category>
    </item>
    <item>
      <title>How to setup a centralised data store using redux in your React application</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Tue, 02 Mar 2021 18:03:59 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/how-to-setup-a-centralised-data-store-using-redux-in-your-react-application-8lj</link>
      <guid>https://dev.to/vignesh_pugaz/how-to-setup-a-centralised-data-store-using-redux-in-your-react-application-8lj</guid>
      <description>&lt;p&gt;&lt;strong&gt;Redux&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Redux is an open source js library for managing your application's state. Redux is commonly used with js libraries like reactjs and frontend frameworks such as angular. A redux store works on the principle of a javascript reducer where the centralised application state is updated with the help of an action dispatcher. An action dispatcher dispatches an action object which describes what is to be done with the application state. An action object is a simple js object with keys "type" and "payload". "type" describes the action to be performed and "payload" is the actual data used to update or mutate the application state. Here's an example of an action object :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{type:'ADD_ITEM',payload:'Android'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;'ADD_ITEM' describes the action event and 'Android' is the data to be mutated in the state.&lt;/p&gt;

&lt;p&gt;To make it clear, go through the following code snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState={
  items:[]
}

function rootReducer=(state=initialState,action){
  switch(action.type){
     case 'ADD_ITEM':
        return {...state,items:[...state.items,action.payload]}
     case 'REMOVE_ITEM':
        const filteredItems=state.items.filter(item=&amp;gt;item!==action.payload)
        return {...state,items:filteredItems}
     default:
        return {...state}
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Create a store with redux&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Upto this point, I hope the concepts of state, action and dispatch objects might be clear. The next question is how do I create a store and update it with the help of action objects. For this, install the redux library using npm or you can go with a cdn if node is not installed in your system.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;redux has made it possible to create a centralised store easily with a single line of code. All you have to do is, pass the reducer as an argument to the createStore() function of redux. This acts as a channel to dispatch your action objects and listen to state updates. Go through the modified snippet below :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {createStore} from 'redux';

const initialState={
  items:[]
}

function rootReducer=(state=initialState,action){
  switch(action.type){
     case 'ADD_ITEM':
        return {...state,items:[...state.items,action.payload]}
     case 'REMOVE_ITEM':
        const filteredItems=state.items.filter(item=&amp;gt;item!==action.payload)
        return {...state,items:filteredItems}
     default:
        return {...state}
  }
}

const store=createStore(rootReducer);

console.log(store.getState());
store.dispatch({type:'ADD_ITEM',payload:'Android'})
store.dispatch({type:'ADD_ITEM',payload:'ios'})
console.log(store.getState());
store.dispatch({type:'REMOVE_ITEM',payload:'Android'})
console.log(store.getState());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Try to guess the outputs of the console.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
.&lt;br&gt;
{items:['Android','ios']}&lt;br&gt;
{items:['Android']}&lt;/p&gt;

&lt;p&gt;This was a just a jist of the redux architecture. As mentioned already, redux is the perfect option for a centralised persistent state that goes well with reactjs.&lt;/p&gt;

&lt;p&gt;Now to connect your store with your react application, install react-redux library. Assuming you are using npm package manager with a module bundler like webpack or browersify :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now wrap your top level component, usually App.js , with a  component, with your store passed as a prop. You can do this in index.js file too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import {Provider} from 'react-redux';

import {store} from './configureStore.js';
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  &amp;lt;StrictMode&amp;gt;
    &amp;lt;Provider store={store}&amp;gt;&amp;lt;App /&amp;gt;&amp;lt;/Provider&amp;gt;
  &amp;lt;/StrictMode&amp;gt;,
  rootElement
);


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

&lt;/div&gt;



&lt;p&gt;The above code snippet assumes you create a store in configureStore.js file in the same way as we did earlier. Now you can use the centralised state in your components without the need to prop drill through the components. Make use of useDispatch() and useSelector() hooks to dispatch an action object and  get state values. Following code snippet gives an idea on how to use these two handy hooks :&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,{useState} from 'react';
import {useDispatch,useSelector} from 'react-redux';
export default (props)=&amp;gt;{
  const [newItem,setNewItem]=useState('');
  const dispatch=useDispatch();
  const state=useSelector();

  function newItemHandler(){
    dispatch({type:'ADD_ITEM',payload:newItem})
  }

  return (
    &amp;lt;div&amp;gt;
    {!state.items.length?&amp;lt;h1&amp;gt;List is empty&amp;lt;/h1&amp;gt;:
      &amp;lt;ul&amp;gt;
         {state.items.map(item=&amp;gt;&amp;lt;li&amp;gt;{item}&amp;lt;/li&amp;gt;)}
      &amp;lt;/ul&amp;gt;
    }
    &amp;lt;input 
     type="text" 
     placeholder="add new item"
     value={newItem}
     onChange={e=&amp;gt;setNewItem(e.target.value}
     /&amp;gt; 
    &amp;lt;button onClick={newItemHandler}&amp;gt;Add New Item&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>react</category>
      <category>javascript</category>
      <category>redux</category>
    </item>
    <item>
      <title>Difference between useCallback(),useMemo() and React.memo()</title>
      <dc:creator>Vignesh Pugazhendhi</dc:creator>
      <pubDate>Mon, 01 Mar 2021 13:57:32 +0000</pubDate>
      <link>https://dev.to/vignesh_pugaz/difference-between-usecallback-usememo-and-react-memo-18i6</link>
      <guid>https://dev.to/vignesh_pugaz/difference-between-usecallback-usememo-and-react-memo-18i6</guid>
      <description>&lt;p&gt;Reconciliation or selective re-rendering is a major boost in the performance optimization of a React application. By selective re-rendering, I mean only those sub-components are re-rendered which witness a change in it's state or props passed to it. This is taken care by the React's virtual DOM, which computes the differences between the DOM and updates the UI efficiently. A component is re-rendered if and only if either of the props passed or it's local state is changed. And when a component is re-rendered, it's child components are re-rendered.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React.memo&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React.memo was introduced in functional components in react v16.6. React.memo is a convenient way to avoid re-rendering in functional components. All you have to do is to wrap the functional component with React.memo() HOC(Higher Order Component). It can be used for both class based and functional components. It compares the props passed and the local state between any two consecutive re-renders and can bail out a component from re-rendering if there is no change in the props and the state. Go through the following code snippet to understand the memoization of components:&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,{useState} from 'react';
import ComponentB from './ComponentB';
import Trainer from './Trainer';

function ComponentA() {
    const [pokemons,setPokemons]=useState(
    ["bulbasaur","charmendar","pikachu"]
);
    const [trainer,setTrainer]=useState('');

    console.log('componentA rendered');

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;Trainer handleTrainer={setTrainer}/&amp;gt;
            &amp;lt;ComponentB pokemons={pokemons}/&amp;gt;
            &amp;lt;span&amp;gt;{trainer}&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

export default ComponentA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import styled from 'styled-components';

function Trainer({handleTrainer}) {

    console.log('Trainer rendered');

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;Input onChange={(e)=&amp;gt;handleTrainer(e.target.value)}/&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

const Input=styled
.input
.attrs((props)=&amp;gt;({type:'text',placeholder:'Trainer'}))`
border:2px solid black;
margin:auto;
margin-bottom:20px !important;
margin-top:10px !important;
max-width:50%;
`;

export default Trainer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import styled from 'styled-components';

function ComponentB({pokemons}) {

    console.log('ComponentB rendered');

    return (
        &amp;lt;React.Fragment&amp;gt;
            &amp;lt;UnorderedList&amp;gt;
                {pokemons.map((pokemon,index)=&amp;gt;{
                    return &amp;lt;ListItem key={index}&amp;gt;{pokemon}&amp;lt;/ListItem&amp;gt;
                })}
            &amp;lt;/UnorderedList&amp;gt;
        &amp;lt;/React.Fragment&amp;gt;
    )
}

const UnorderedList=styled.ul`
list-style-type:none;
`;
const ListItem=styled.li`
border:1px solid transparent;
margin:auto;
margin-top:20px !important;
width:50%;
background:#00e6ac;
color:white;
text-transform:capitalize;
`;

export default ComponentB;


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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Code breakdown&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ComponentA is the parent component of ComponentB and Trainer. Local state pokemons is passed as a prop to ComponentB and setTrainer function is passed as a prop to Trainer. When the application loads for the first time, the parent component along with it's children are rendered. You can console.log and check the number of rendering in your browser's developer tools. For every state update of the ComponentA, both ComponentB and Trainer are re-rendered,which we do not want to. To avoid unnecessary renderings, wrap both the children components with React.memo() HOC. Wrapping the components with React.memo() compares the props between two consecutive renders and bails out unnecessary re-renders of it's children components. Though it can memoize the components and boost the performance of the application to a certain level, there is always a catch. A good use case where this can be used is when there are atleast 10 nested components with complex computations. Comparison of props for 2-3 components can be little costly in terms of memoization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UseCallback&lt;/strong&gt;&lt;br&gt;
Suppose we pass a callback function clearTrainer() to ComponentB through props. The purpose of this function is to clear the trainer state to empty string. Now,run the application and you should see 'componentB rendering' in your developer console. This turns out to be unexpected as ComponentB is wrapped with React.memo(). For this to be understood,we need to understand function equality in javascript. Every function in js is an object. For two objects to be equal,it's necessary for both of them to be of same definition and share same location in memory. Now every time ComponentA is re-rendered,a new instance of clearTrainer() function is created. So for subsequent re-renders,we are passing two different instances of the same function definition and thus ComponentB also re-renders. To solve this,we need to wrap the callback function with useCallback() hook. Now useCallback takes two arguments-one is the callback function and second is an array of dependencies for which a new instance of the callback function is to be created. ComponentB's UI depends upon the prop pokemons. So,pass pokemons as a dependency.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ComponentA() {
    const [pokemons,setPokemons]=useState(
    ["bulbasaur","charmendar","pikachu"]
);
    const [trainer,setTrainer]=useState('');

    const clearTrainer=useCallback(()=&amp;gt;{
        setTrainer('');
    },[pokemons]);

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;Trainer handleTrainer={setTrainer}/&amp;gt;
            &amp;lt;ComponentB 
            pokemons={pokemons} 
            clearTrainer={clearTrainer}
            /&amp;gt;
            &amp;lt;span&amp;gt;{trainer}&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;useMemo&lt;/strong&gt;&lt;br&gt;
useMemo() is similar to useCallback().The only difference between these two hooks is, one caches the function and the other caches any value type. Consider a situation where you have to render a long list of elements and each element calls an expensive function for it to render some information. During the first render, the thread is completely blocked until the expensive functions are executed. In subsequent re-renders useMemo() makes use of the memoized value to avoid calls to those expensive functions. This can be understood with the following code snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Items=({list})=&amp;gt;{
  const listContent=list.map(item=&amp;gt;{
    return {
     name:item.name
     price:item.price
     priceWithoutVat:expensiveFunctionOne(item.totalPrice,item.basePrice)
    }
  });
  return &amp;lt;div&amp;gt;{listContent}&amp;lt;/div&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's assume this code snippet is in a component which re-renders frequently for some obvious reasons. Now to avoid the complex computations, we memoize the value of listContent. To do this,wrap  it in useMemo() hook. useMemo() takes two arguments. One is the value to be memoized and the other, a list of dependencies for which this value is to be recalculated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Items=React.useMemo(({list})=&amp;gt;{
  const listContent=list.map(item=&amp;gt;{
    return {
     name:item.name
     price:item.price
     priceWithoutVat:expensiveFunctionOne(item.totalPrice,item.basePrice)
    }
  });
  return &amp;lt;div&amp;gt;{listContent}&amp;lt;/div&amp;gt;
},[list])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>react</category>
      <category>javascript</category>
      <category>reacthooks</category>
    </item>
  </channel>
</rss>
