<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shubham Sharma on Medium]]></title>
        <description><![CDATA[Stories by Shubham Sharma on Medium]]></description>
        <link>https://medium.com/@shubham-sharma75089?source=rss-d91bd3e44dc2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SwlQ1_AfvXpQs6qPJQMkpQ.jpeg</url>
            <title>Stories by Shubham Sharma on Medium</title>
            <link>https://medium.com/@shubham-sharma75089?source=rss-d91bd3e44dc2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:40:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubham-sharma75089/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Strategy Design Pattern: Explained]]></title>
            <link>https://shubham-sharma75089.medium.com/strategy-design-pattern-explained-81eb8690ff8a?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/81eb8690ff8a</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 04:04:47 GMT</pubDate>
            <atom:updated>2023-01-31T04:12:54.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine that you are working in a company which requires you do design a simple game application for kids. This application involves simulating the behaviours and activities of different types of <strong>Animals</strong>. The general behaviours may include the animals’ appearances, the different kinds of sounds they make, how they rest. Thus, you come up with a basic OO (Object Oriented) solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*a4CHnsJz9itVU7rsngoUlg.png" /><figcaption>Fig. 1</figcaption></figure><p>In Figure 1, an inheritance based solution has been employed to derive various concrete classes out of a base class Animal. All the concrete animal classes inherit from the abstract class Animal. The methods eat and makeSound have been defined in the abstract class Animal. This prevents code duplication in each of the concrete child classes. The display method is abstract and is overridden in each of the inherited classes as each animal looks different. At the initial look, this solution looks great.</p><p>But wait. Let’s say another requirement comes from the business side that now we will have a toy animal made of plastic too. However, this toy animal neither eats nor makes any sound. For this class to be placed in the old hierarchy, both the eat and makeSound methods need to be overridden</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*rINjrz6lF4vg4FbkeG3GEA.png" /><figcaption>Fig. 2</figcaption></figure><p>If we analyse, our point of using inheritance was to reduce code duplication. However, every new child class may or may not implement the functions of the base class. Even if majority of them do, each might do it differently. For example, a tiger would eat only deer but a pigeon would eat only worms. So in this case, behaviour of eating is common but the inner details vary across the child classes. Thus, what we thought was a great use of inheritance for the purpose of reuse has not turned out to be that great when it comes to extending and maintaining our code for future use cases.</p><h3><strong>Let’s try with an interface</strong></h3><p>Inheritance is probably not the answer. The requirements from the business team might change every six months in ways which has not been decided before and the spec will keep changing. The only option you would have would be to keep on overriding eat() and makeSound() method in each of the Animal child classes. How to go about next?</p><p>You can probably use interfaces like CanEat or CanMakeSound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*ySBRoz-fAGxi9oyti5EjFA.png" /><figcaption>Fig. 3</figcaption></figure><p>Although interfaces solve the problem of the plastic tiger not eating, not making a sound and not having to override the eat and makeSound methods in its class, the original point of using OO design to reduce code duplication does not hold now. Each implementation of pigeon or snake will have to separately define its own eat and makeSound method. This can be a maintenance nightmare. Once these methods are defined in the concrete subclasses, any change in spec ie change in eating or sound behaviour would mean change in the respective classes. This violates the second SOLID design principle ie a class should be open for extension and closed for modification.</p><h3>Encapsulate what varies</h3><p>There are behaviours of the Animal class which vary across each concrete implementation. These can include eating behaviour, sound etc. Other behaviours like rest do not require frequent change. Then why not encapsulate these changing behaviours into one interface. You can have distinct classes which represent different behaviours implementing from this common interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*-tB7DImkl8CraSIODva1PQ.png" /><figcaption>Fig. 4</figcaption></figure><h3>Program to an interface, not an implementation</h3><p>The whole point of this exercise is to keep things flexible and ensure that further addition of any new behaviour in the animal class does not lead to a change or method overriding in any of the already existing concrete classes of the animals. Thus, it is important for you to make sure that Animal class does not implement the interfaces FoodBehaviour or SoundBehaviour. Instead, there should be separate classes whose only point of existing is to represent a behaviour. These behaviour classes will implement the interface. Herbivore is class let’s say which implements the EatBehaviour interface. The core logic will be inside these behaviour classes. Thus, Animal class will have a class variable of the type EatBehaviour or SoundBehaviour. Any concrete class which implements these behaviours can be assigned to these variables. Because of polymorphism, all the behaviours can be assigned to the variable of type EatBehaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*-P129aGlDJ4hqBo1u4KusQ.png" /><figcaption>Fig 5</figcaption></figure><p>The point is to exploit polymorphism by programming to a super type so that the actual runtime object isn’t locked into the code. The declaration type of the variables should be a super-type, usually an abstract class or interface, so that objects assigned to that variable can be of any concrete implementation of the super-type. Thus, classes declaring them doesn’t have to know about the actual object types.</p><p>Let’s understand this with the help of an example,</p><p>Programming to an implementation would mean</p><pre>Dog d = new Dog();<br>d.bark();</pre><p>Declaring the variable “d” as type Dog (a concrete implementation of Animal) forces us to code to concrete implementation</p><pre>Animal animal = new Dog();<br>animal.markSound();</pre><p>We know it is a dog, but we can use the animal reference polymorphically. In other words, we have now programmed to an interface(super-type) not to an implementation.</p><p>To do it even better, we can assign the concrete implementation at runtime rather than hardcoding it</p><pre>Animal animal = getAnimal();<br>animal.makeSound();</pre><p>We don’t know beforehand what concrete implementation of Animal will be assigned to the animal variable. But we know for sure that since the concrete implementation inherits or implements the Animal super-type (abstract class or interface), it knows how to handle makeSound.</p><h3><strong>Implementing the eat and sound behaviour</strong></h3><p>Similar to the EatBehaviour as shown in Fig 5 we can have a sound behaviour also with its different concrete implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*PDCllng52UBI2mD4R_lTgw.png" /><figcaption>Fig 6</figcaption></figure><p>In case any new kind of EatBehaviour or SoundBehaviour needs to be incorporated in our application, simply we would create a new class which implements these behaviour interfaces. These behaviour implementations are no longer hidden in the Animal class. Thus, to add a new behaviour we do not have to modify any of our existing behaviours or touch the Animal class which uses that behaviour. Hence, we are able to satisfy our second SOLID principle that a class should be open for extension but closed for modification. Following is the java code which represents our classes.</p><pre>public abstract class Animal {<br>  EatBehaviour eatBehaviour;<br>  SoundBehaviour soundBehaviour;<br>  public Animal() {}<br>  public void setEatBehaviour(EatBehaviour eatBehaviour) {<br>    this.eatBehaviour = eatBehaviour;<br>  }<br>  public void setMakeSoundBehaviour(SoundBehaviour soundBehaviour) {<br>    this.soundBehaviour = soundBehaviour;<br>  }<br>  public void eat() {<br>    this.eatBehaviour.eat();<br>  }<br>  public void makeSound() {<br>    this.soundBehaviour.makeSound();<br>  }<br>  public abstract void display();<br>  public void rest() {<br>    System.out.println(&quot;Animal is resting&quot;);<br>  }<br>}</pre><pre>public interface EatBehaviour {<br>  public void eat();<br>}</pre><pre>public interface SoundBehaviour {<br>  public void makeSound();<br>}</pre><pre>public class EatWorms implements EatBehaviour {<br>  public void eat() {<br>    System.out.println(&quot;Eat Worms&quot;);<br>  }<br>}</pre><pre>public class EatDeer implements EatBehaviour {<br>  public void eat() {<br>    System.out.println(&quot;Eat Deer&quot;);<br>  }<br>}</pre><pre>public class EatRats implements EatBehaviour {<br>  public void eat() {<br>    System.out.println(&quot;Eat Rats&quot;);<br>  }<br>}</pre><pre>public class Hiss implements SoundBehaviour {<br>  public void makeSound() {<br>    System.out.println(&quot;Hiss&quot;);<br>  }<br>}</pre><pre>public class Coo implements SoundBehaviour {<br>  public void makeSound() {<br>    System.out.println(&quot;Coo&quot;);<br>  }<br>}</pre><pre>public class Growl implements SoundBehaviour {<br>  public void makeSound() {<br>    System.out.println(&quot;Growl&quot;);<br>  }<br>}</pre><p>The above are the main classes used in our implementation. Each eat or sound behaviour is a concrete implementation of a generic interface. Animal contains a variable of the type generic interface and concrete implementations are flexibly assigned to the Animal class.</p><pre>public class Tiger extends Animal {<br>  public Tiger() {<br>    this.setMakeSoundBehaviour(new Growl());<br>    this.setEatBehaviour(new EatDeer());<br>  }<br>}</pre><pre>public class Simulator {<br>  public static void main(String[] args) {<br>    Animal tiger = new Tiger();<br>    tiger.makeSound();<br>    tiger.eat();<br>    tiger.setEatBehaviour(new EatRats());<br>    tiger.eat();<br>  }<br>}</pre><p>The terminal shows output like as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Knce1kxLQ2YauJ56pfrR8g.png" /></figure><p>Thus, using the above implementation we are not just able to add new eat or sound behaviours but also change the behaviours at runtime as nothing is hardcoded.</p><h3><strong>The Big Picture</strong></h3><p>The different ways of eating or making sound can also be generalised as family of algorithms. Our client makes use of an encapsulated family of algorithms for eating and making sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVnKaM-JdhKmnPIcyspWyQ.png" /><figcaption>Fig 7</figcaption></figure><p>As we look closely at figure 7, we find that each animal has a HAS-A relationship with Eat Behaviour and Sound Behaviour. When two classes are put together, it is called a <strong>composition</strong>. So instead of one class inheriting the other class, animals get their behaviour by being composed with the right behaviour object. Composition gives us a lot of flexibility as helps us keeping the animal classes and the behaviour classes loosely-coupled. Moreover, it lets us change the behaviour class for an animal at runtime.</p><p><strong>Give a pat on your back! </strong>For having shown the patience to complete the full article. We just used the Strategy design pattern which can be succinctly defined as:</p><blockquote><strong>The Strategy Pattern</strong> defines a family of algorithms, encapsulates each one and makes them interchangeable. Strategy lets clients vary independently from clients that use it.</blockquote><p>Thanks for bearing with me and reading the full article. Please find the github link to the code <a href="https://github.com/abhirath14/StrategyDesignPattern">https://github.com/abhirath14/StrategyDesignPattern</a></p><p>Special mention to the Head First Design patterns by Eric Freeman and Elisabeth Robson for helping me develop understanding of the subject.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81eb8690ff8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does the single-threaded javascript manage to do multiple tasks together?]]></title>
            <link>https://shubham-sharma75089.medium.com/how-does-the-single-threaded-javascript-manage-to-do-multiple-tasks-together-5f58fc180a7a?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f58fc180a7a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[call-stack]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[single-threaded]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 10:31:13 GMT</pubDate>
            <atom:updated>2021-12-12T11:10:10.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kc9I_4TPewYFKonxQcNkNg.png" /></figure><p>We know of javascript as a single-threaded, asynchronous, concurrent and non-blocking language. But the first question which arises after reading this is that how can a language be single-threaded ie able to do one task at a time and yet be asynchronous, concurrent and non-blocking. Single-threaded implies that javascript has one call stack which stores the sub-routines or functions called. However, just like any stack, only the function at the top of the call stack can be executed at any point of time. And that function can be time taking. It might involve a network call, running a while loop for 1,000,000 iterations or taking some input from the user. Anything which takes long, if present in the call stack, will block the execution of everything apart from it. Javascript is used on the browser. Thus, it means that if something like a network request is made on the browser, then the user will not be able to click a button or fill a form on the browser. But that is not what users generally experience on the web. Users are able to listen to music, watch a video and upload or download files simultaneously on the web browser.</p><p>To understand this phenomenon, we have to deep dive into the internal workings of javascript. When you execute a script, the JavaScript engine creates a Global Execution Context (GEC) and pushes it on top of the call stack. Whenever a function is called, the JavaScript engine creates a Function Execution Context (FEC) for the function, pushes it on top of the Call Stack, and starts executing the function.</p><p>Let’s understand first how the call stack works with only synchronous code. In the infographics, the GEC and FEC are deliberately omitted to reduce clutter. Initially, the call stack will be empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*cHq11Pjpvb-ZxDhtIDHuBg.png" /><figcaption>1. Empty call stack</figcaption></figure><p>First of all, <strong>console.log(‘Begin’) </strong>will be pushed inside the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*4-evQzMozdquq3A_iyaCFA.png" /><figcaption>2. Call stack</figcaption></figure><p>Since, console.log(‘Begin’) is a non-blocking I/O operation, it will immediately print <strong>Begin </strong>on the console. Thus, this item in the stack will be popped out after the execution. Then, the call stack again becomes empty as shown in 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*cHq11Pjpvb-ZxDhtIDHuBg.png" /><figcaption>3. Empty call stack</figcaption></figure><p>Then the next command or function to be executed is pushed into the call stack ie <strong>saySomething() </strong>in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*tk_iIO_J4RITkvsxNw4Bfg.png" /><figcaption>4. Call stack</figcaption></figure><p>It further calls printHello(), so that will be pushed into the stack</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*Lz0eA7Z8CM7tD1RuhmoCzQ.png" /><figcaption>5. Call stack</figcaption></figure><p>Then, console.log(‘Hello’) will be pushed into the stack as that is contained inside printHello().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*Pi_BPZIHwjoGqOEeqXmvDg.png" /><figcaption>6. Call stack</figcaption></figure><p>Now <strong>hello</strong> will be printed and <strong>console.log(‘Hello’)</strong> will be popped out of the call stack</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*Lz0eA7Z8CM7tD1RuhmoCzQ.png" /><figcaption>7. Call stack</figcaption></figure><p>Then, <strong>printHello()</strong> will be popped out of the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*tk_iIO_J4RITkvsxNw4Bfg.png" /><figcaption>8. Call stack</figcaption></figure><p>Finally, saySomething() will be popped out of the call stack.</p><p>If one does a grep on the v8 source code which is the runtime for javascript in the browser, one will not find anything like setTimeout(), DOM or XMLHttpRequest. It is surprising because one of the first things an newbie learns about javascript is exactly these. Then, how is one able to use setTimeout in the browser or make a network request from the browser.</p><p>The answer to this is Web Apis. Web Apis are not part of the javascript language but are built on the core of javascript to give you extra functionality. They interact with the operating system’s async handlers to perform the async operations while abstracting the complexities from the javascript runtime ie v8. If one is using Node.js, web apis get replaced with libuv library written in C++. This library interacts with the operating system’s async handlers in that case.</p><p>But the next question is that once the web apis complete the long task, how do they return the data back to the user. They cannot pop the data in the browser at any moment of time as it might be out of context. For accomplishing this, an <strong>event loop </strong>and a <strong>callback queue </strong>are used. Callback queue, also known as the Task queue, is a FIFO queue which stores those async tasks which are completed and are ready to be pushed into the call stack. Event loop continuously checks if the call stack is empty, and if it is then it pushes the first element of the callback queue on the call stack.</p><p>We can understand this in more detail through an example.<br>Let’s assume that we have a piece of code which involves an async function printDelayedHi(). Initially, the call stack is empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*xIx_iB-b7E_URqO6T0ABfg.png" /><figcaption>Step 1</figcaption></figure><p>Now the control flows to the first statement of code ie<strong> console.log(‘Begin’)</strong>. It is pushed in the call stack as in Step 2, executed and the string <strong>Begin </strong>is printed on the console after it is popped out as shown in Step 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ET9Bx0MSq2YNVNpu1HQ3ew.png" /><figcaption>Step 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*gv7o0bDprzeHCjETcnMTng.png" /><figcaption>Step 3</figcaption></figure><p>Then, the function printDelayedHi() is pushed into the call stack as in Step 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*YFvLrvUCJGGKQw3JBmh9Cg.png" /><figcaption>Step 4</figcaption></figure><p>In Step 5, the underlying code inside printDelayedHi() which is a <strong>setTimeout(() =&gt; {console.log(‘Hi’)}, 3000)</strong> is pushed into the stack. Since, it is an asynchronous function, it will be handled by the Web APIs. Thus, this snippet is popped out of the call stack and given to Web APIs as in Step 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ZtpFenwBm5t5r1J43R624w.png" /><figcaption>Step 5</figcaption></figure><p>The setTimeout snippet will take 3 seconds in the Web APIs. Meanwhile, printDelayedHi() will be popped out of the call stack as in Step 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*QD1eUkjQoAiIBU_2byE7tw.png" /><figcaption>Step 6</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*PedBqWAVigeViGfhhTscMw.png" /><figcaption>Step 7</figcaption></figure><p>Then, console.log(‘End’) is pushed into the call stack as in Step 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*qeQf5rd_9luKmU_i36-URA.png" /><figcaption>Step 8</figcaption></figure><p>It gets executed immediately and printed on the console as in Step 9. And the call stack becomes empty again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*BwPDqfGctQX5BIe8jRCWSw.png" /><figcaption>Step 9</figcaption></figure><p>Now, once 3 seconds elapse, console.log(‘Hi’) is taken out from the Web APIs and pushed in the callback queue as in Step 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*pO2Xe-F22ndiSkeVgYeD_g.png" /><figcaption>Step 10</figcaption></figure><p>Then comes the role of the event loop. The event loop, checks if the call stack is empty and if it is, then it puts the front element of callback queue into the stack as in Step 11. Please note, that if there were something already inside the call stack, then the callback queue will not be dequeued and nothing will be pushed in the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*eYy1jNDdG4GKR9u9A5ERoA.png" /><figcaption>Step 11</figcaption></figure><p>Finally, as in Step 12, the top element of call stack ie <strong>console.log(‘Hi”)</strong> is popped out of the stack and displayed on the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ImnOQdky6vXeQk4om-sQLw.png" /><figcaption>Step 12</figcaption></figure><p>In this way, javascript managed to run a <strong>setTimeout</strong> function which is an asynchronous function despite being single-threaded and having only one call stack. In case of browser, it uses Web APIs and in case of Node js, it uses libuv library. Apart from that it uses a callback queue and an event loop. Javascript is a powerful language which can handle user interface level logic as well as can run web servers. It is quite easy to learn and this makes it one of the most popular languages of the world. I hope this article helped you understand the inner working of javascript while it operates in your browser as well as on your server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f58fc180a7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Shah Rukh Khan Phenomenon]]></title>
            <link>https://shubham-sharma75089.medium.com/the-shah-rukh-khan-phenomenon-91ec4fac2db9?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ec4fac2db9</guid>
            <category><![CDATA[shah-rukh-khan]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[1991]]></category>
            <category><![CDATA[economic-reforms]]></category>
            <category><![CDATA[economy]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 06:23:28 GMT</pubDate>
            <atom:updated>2021-07-13T06:34:06.313Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_W7UP7O7qAA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_W7UP7O7qAA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_W7UP7O7qAA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/166f86a63864f8831fef6721484c5b5e/href">https://medium.com/media/166f86a63864f8831fef6721484c5b5e/href</a></iframe><p>Few days ago I came across an ad of BYJUs featuring the mega star Shah Rukh Khan. Co-incidentally, last month SRK completed his 29 years in the Hindi film industry. For a has been star, who delivered his last good film close to 15 years ago ie Chak de India, I sometimes wonder how SRK has managed to stay relevant. Why he still is the favourite of brands and for that matter why startups like BYJUs and Big basket choose him as their ambassador over any new age star who is making good films in today’s time. Here is my understanding of this SRK phenomenon.</p><p><strong>Face of post-liberalisation India:<br></strong>SRK started his career in the 90s with anti-hero roles in Deewana, Darr and Bazigar. At that point India was changing very rapidly because of the fruits of 1991 economic reforms were reaching the people. This change was much more prominent in the metro cities. The creed in our society was no longer socialism. SRK became the star of this post-liberalisation India. In every way, in the kind of roles he did, in the way he carried a global persona and appealed to an NRI audience, in the kind of brand endorsements he did. He makes the transition of Hindi cinema where the hero changes from a Hindi speaking, non-anglophile person from the cow-belt to an English speaking person from the metropolitan city with all the brand consciousness and sophistication of an urban male. The scenes in DDLJ were from Europe and India signalling the era of globalisation. These created an amazing cocktail where you could be western and cool and yet be rooted in Indian culture. The brands in Kuch kuch Hota hai, Polo and Tommy Hilfiger were all on SRK’s chest. Individualism rose in society and so did individual ambitions. In Baazigar, the hero pursued revenge purely based on individualistic reasons. Not for a patriotic cause or for a social cause or a community cause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkUY4rpfm_WMCq0tEb2qqw.jpeg" /><figcaption>SRK wearing a POLO T-shirt in Kuch Kuch Hota Hai</figcaption></figure><p><strong>SRK as a brand:<br></strong> He was one of the first stars to do advertisements. From Pepsi to Fruity, from Nerolac to Hyundai, from Dishtv to Fair and Lovely, from Axis Bank to Hewlett Packard and now Vimal Pan masala to BYJUs; SRK is the child of consumerism. While doing all that he built a brand for himself also. His charm and effective style of communication, with a dose of humour attracts eyeballs. This is complemented by the fact that he is a well-read man and most importantly a self-made man. He has a rags to riches story to tell. All that makes him an icon for the aspirational youth of today’s day and age.</p><p><strong>Touch of femininity:</strong><br> Anything which was considered unmanly or pansy earlier became the traits of this new male symbolised by SRK. I mean can a Sanjay Dutt or a Salman Khan do an ad for LUX in bathtub and talk about what is their khoobsurti ka raaz? But SRK does that. He drops into feminine spaces so comfortably and confidently. You would see him cutting vegetables in the kitchen in Kal Ho na ho, going to temple in Kuch kuch Hota Hai, crying for a woman and wearing his heart on his sleeve in Veer Zara, dealing with insecurities and infidelity in marriage in Kabhi Alvida Na Kehna etc. He does all that so effortlessly and confidently. So it is longer that mard ko dard nahi Hota for him. Why would women not fall for him?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_lf7_AcsIqI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_lf7_AcsIqI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_lf7_AcsIqI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ed85dff4863a35c6c246c7ed7cb1b3/href">https://medium.com/media/97ed85dff4863a35c6c246c7ed7cb1b3/href</a></iframe><p><strong>Appeal to children and their parents:</strong><br>SRK in his intellectual persona displays a great regard for academics and sports. He was a sportsman in his teens. Listening to his convocation speeches and interviews, one can figure out that he is a very well read man too. His association with shows like KBC, Kya App Panchvi Pass se Tez Hain, TED Talks reveal his regard for education and knowledge. That’s why I believe BYJUs chose him over anyone else. Above all of that, SRK is known as a family man who enjoys spending most time apart from work with Gauri and his children. All this makes parents also to like him.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVnnXAiTOLbo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVnnXAiTOLbo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVnnXAiTOLbo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e43418fee7b3b8949148c7f04fbc8e/href">https://medium.com/media/15e43418fee7b3b8949148c7f04fbc8e/href</a></iframe><p><strong>Style of communication and confidence:<br></strong> Brands know very well that if SRK is going to be on television, whether in advertisements, award shows or chat shows, people are going to watch and listen to him. His style of communication appears genuine and authentic. However, it does not mean he sounds like Arun Govil from Ramayan. He supplements his genuineness with a heavy dose of wit and humour. He balances these two very very effectively. So he neither appears boring nor like a jerk. His ability to make fun of himself shows his confidence. His admission about his not so good looks, not so perfect acting, not so right choice of films and still how managed to succeed despite all that shows his honesty and lack of any complex or insecurity. He not just achieved moderate amount of success but super duper stardom, the kind of stardom we might not see for long. He is not apologetic about his success and money. His philosophy is that he came to Bombay with nothing, he didn’t have a godfather and now that he is successful, he wants to enjoy his success.</p><p>SRK’s rise mirrors the story of a nation coming of age and embracing the opportunities of the new world. He symbolises the intelligence of new India, he symbolises the energy of new India, he symbolises the confidence of new India. He represents the liberal India both in the social and economic sense.<br>Source: Discovery Documentary on SRK</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ec4fac2db9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST APIs Explained in 5 mins]]></title>
            <link>https://medium.com/codex/rest-apis-explained-in-5-mins-b8f83399c6cf?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8f83399c6cf</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[http-server]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sat, 19 Jun 2021 05:40:19 GMT</pubDate>
            <atom:updated>2021-06-20T13:11:27.958Z</atom:updated>
            <content:encoded><![CDATA[<p>There are already so many technical definitions of what is a REST API. However, most definitions are not very understandable. This post tries to explain what a REST API is and what pain point it solves in simple English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*9mhEcbqWgKRMGu47Jeh7mQ.png" /><figcaption>Basic architecture of a web application</figcaption></figure><h3>Background</h3><p>One way to make any web app work is to create the data embedded UI at the server side and pass the whole UI in the form of HTML to the client. One can use a templating language like EJS or PUG to generate HTML code on the backend server.</p><p>However, not every client wants the response in the form of an HTML template. Think about mobile apps which do not use HTML. We might want to create service APIs to third party applications just like Google maps does. One does not have any clue about their user interface. One only needs the data and the client is expected to fill this data in the interface generated by the itself.</p><p>Mobile apps might want to use different libraries from Java, Swift, Objective C etc. Web apps might want to use Angular.js, Vue.js or React.js Thus, deciding the UI at the backend might not be a good decision. Also, service apis to third party applications do not require the user interface, they just require the data.</p><p>Also, these days SPAs (Single page apps) are used at the client side. They do not expect the URL to change for changing the UI. It makes the user experience bad. They just need to use browser rendered javascript to change the UI. You click around then you don’t wait for page refresh. Data interaction and population happens in the background.</p><p>Thus, the problem we understood so far is the problem that UI and data need to be decoupled so that data can be used across multiple client side platforms.</p><p>A different kind of response is needed from backend. We need to transfer data instead of UI. We leave it to the client (mobile, SPA, third party application) to do whatever it wants to do with the data.</p><h3>REST (Representational State Transfer).</h3><p>A client-server architecture is made up of requests, responses and resources. Resource is the target of the HTTP request on which an action is requested. It can be an entry in DB, an image, a document or anything. A client makes an operation on a resource through an HTTP request and expects a response giving information about execution of the desired action on resource.</p><p>Now, in which format to expect the data from server. Below is the diagram showing the different type of data formats which can be rendered by an API response with their unique characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*fZLg8UFzm67yyNsAd2NLGw.png" /><figcaption>Different types of data formats</figcaption></figure><p>The most suited data format for the REST APIs is the JSON (Javascript Object Notation). This allows one to get structured data which is concise and easily readable by machine as well as by humans. Also, it can be easily converted to a JS object and JS is what runs in the browser eventually.</p><p>We know from our previous knowledge, what an API (Application Programming Interface) is. It is a contract between an information provider and an information user with a set definitions and protocols. In other words, if you want to interact with a computer or system to retrieve information or perform a function, an API helps you communicate what you want that system to do so it can understand and fulfil the request.</p><p>Now let’s understand what an API endpoint is. An API endpoint is a combination of an HTTP URL and an HTTP verb. An HTTP verb defines the nature of the request. What change on the resource will the request bring? Will it just fetch the resource, create a resource, modify it, replace it and so on?</p><p>Thus, GET <a href="https://example.com/?user_id=1">https://example.com?user_id=1</a> is an endpoint. It represents that we want to get the resource with user_id 1 from the url which represents example.com server. <br>The following infographic shows the different HTTP verbs with their use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*dM8X90R27RPKASaMYxalJw.png" /><figcaption>HTTP Verbs</figcaption></figure><p>Using the right verb makes the API endpoint more predictable. Although, it is only a matter of convention. You many use any verb and execute the code of your choice on the server. You may make a GET request create an entry in database. That is perfectly possible. But it will only create confusion to the client as he would not be able to predict the behaviour of the API endpoint.</p><p>Now let’s come to the definition. When a client makes a request via a RESTful API, it transfers a <em>representation of the state</em> of the resource from the client to the server. The state can mean information about the client ie who the client is, what is he authorised to do, which resource is he requesting to get or change on the server, what changes he wants to do on that etc.</p><p>The server does not know beforehand who the client is, when he last requested any resource. Each request is un-connected to the previous request and no session of the user is maintained at the server side. For cases where maintaining information related to user is essential especially related to user’s identity, JWT tokens are used by the client in auth headers to authenticate and authorise itself. The tokens are again stored at the client and not at the server. The server only generates or verifies the token, but never stores it. Thus, REST API is totally <em>stateless.</em></p><p>The REST convention profusely makes use of headers to transfer meta data about the resource. All the authorisation tokens, what kind of response to expect in terms or format etc are all communicated through request and response headers.</p><p>Finally to summarise, following are the main principles of REST architecture:</p><ul><li>A client-server architecture made up of clients, servers, and resources, with requests managed through HTTP</li><li><a href="https://www.redhat.com/en/topics/cloud-native-apps/stateful-vs-stateless">Stateless</a> client-server communication, meaning no client information is stored between get requests and each request is separate and unconnected.</li><li>Uniform interface: Clearly defined API endpoints, and request and response data structure. One is able to exactly define the state of the resource in the client request.</li><li>Layered system: The server may forward the HTTP request to other servers and the client would not have visibility to that</li><li>Cacheable data that streamlines client-server interactions. The data sent by the server to the client can be cached and once it expires, the data can be requested again</li><li>Code-on-demand (optional): the ability to send executable code from the server to the client when requested, extending client functionality. However, it is used very rarely.</li></ul><h3>Conclusion</h3><p>RESTful architecture by far the most popular in today’s times. Very much used, very much spoken about, however now very well understood. This post is an attempt to explain the REST principles in the simplest language possible. If you like this post and find it relevant please give some claps on medium and share it with relevant people. Thanks you very much for reading this!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8f83399c6cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/rest-apis-explained-in-5-mins-b8f83399c6cf">REST APIs Explained in 5 mins</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker: Why and What?]]></title>
            <link>https://shubham-sharma75089.medium.com/docker-why-and-what-6970649ef639?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6970649ef639</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sat, 22 May 2021 09:14:01 GMT</pubDate>
            <atom:updated>2021-05-22T17:10:00.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine that you are trying to install a software on your local machine. First you download the installer file, then you run it and if you are lucky, then it gets installed. But if you are not, then you get an error because of some dependencies which are not on your machine. In that case, you try to trouble-shoot it by installing those dependencies. Then, you re-run the installer. If you are unlucky again, then another error comes up and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*SjXzIs2HZtJHUwqJgwox_A.png" /><figcaption>Docker logo</figcaption></figure><p>Hence, it shows that we need a platform where we can run any application and just forget about whether we have the required dependencies for running the application in our local machine or not. <strong>Docker</strong> does exactly that for us. Docker is an ecosystem of different projects for creating and running <strong>containers. </strong>Now what are containers, we will come to that next.</p><h3>Installation</h3><p>Before proceeding forward, I would suggest that you create a free account on <a href="https://hub.docker.com/">docker hub</a>.</p><p>While signing up, you have to choose a docker id and password and enter your email. Docker id is a username of sorts and will be publicly visible to other people.</p><p>Then, download docker (community edition) for windows/mac/linux and run it.</p><p>Once you run it, you would see a logo with a whale with boxes on top on your top right. It might take a couple of minutes to get started. You can click on this icon and it will show you an option to log in.</p><p>Clicking on login will show you a pop-up where you can enter your docker Id and password. Once you are done, you can verify that docker is running by going to your terminal and entering <strong>docker version</strong>. If you get something like command not found, then that means docker is not installed. However, if you get a verbose description of docker and related commands then it means that docker installation is successful.</p><p>Now that docker is installed, lets run <strong>docker run hello-world </strong>on your terminal. Running it for the first time gives this response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XExzU027N62Gac_GNtahbg.png" /><figcaption>Terminal output</figcaption></figure><p>Let’s analyse what just happened. When we run <strong>docker run hello-world, </strong>something called Docker <strong>Client </strong>checked locally for the hello-world image in image cache. It could not find that so it reached out to something called Docker <strong>Server </strong>or Docker <strong>Daemon</strong>. The Docker daemon pulled the “hello-world” image from Docker <strong>Hub </strong>which is a free public repository of images<strong>. </strong>From the Docker Image, a Docker <strong>Container </strong>was created. It is nothing but an instance of an image running a program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*kxIoepZoI_gJ6_v0MZfuYw.png" /><figcaption>Docker ecosystem</figcaption></figure><p>One also notices that when one runs <strong>docker run hello-world </strong>again, then it does not show the message that ‘Unable to find hello-world:latest locally’. It shows that the image downloaded from docker hub has now been stored locally in the image cache.</p><h3>What is a container and what is an image?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*gyIXc-9hbLPBuLOrv2E9RA.png" /><figcaption>Relationship between an image and a container</figcaption></figure><p>To understand a container, let’s get some context about how an operating system functions on our computer. An operating system has a continuously running process called <strong>Kernel. </strong>Let’s say that we are running some applications on our computer. We have opened the chrome browser, command line terminal, a text editor and the slack app. Each of these requires all kinds of memory resources, networking resources, I/O resources etc which are provided by the computer hardware. Now how does each of these applications communicate with the hardware? Essentially, it makes something called a <strong>System Call</strong>. It is a request to kernel so that it can allow the application to interact with the hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*u-Ntd3V37e09_GIKHnFPeQ.png" /></figure><p>Now imagine, that in some hypothetical world, <strong>Chrome</strong> requires python <strong>version 2</strong> as dependency, while <strong>Slack</strong> requires python <strong>version 3</strong> as dependency. For some reason, at one point of time only one version of python can be there in the hard disk. So chrome would work properly but slack would not work properly. Although, this is a make believe situation, it gives us the basic motivation for using a container.</p><p>Now how can we solve this problem? We use the operating system technique called <strong>Namespacing</strong> to segment the hard disk resources and <strong>Control group </strong>to limit the amount of resources used per process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*kf5Z9cahK-L5l2W-HDD5lQ.png" /><figcaption>Namespacing</figcaption></figure><p>Now while the application ie either chrome or slack makes a <strong>System Call </strong>to hard disk, the kernel makes out whether to direct it to the segment of hard disk containing python v2 or python v3.</p><p>In this way, one is able to run both chrome and slack on one’s machine. Thus, namespacing is nothing but <strong>isolating hardware resources per process or a group of processes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*BStEPgNJSpQ2MtbFHcDJVA.png" /><figcaption>Dotted box comprises of a container</figcaption></figure><p>Now, a container is something which is comprised in the red dotted rectangle. It has a running application or program or process that sends a system call to kernel. The kernel is going to process that request and direct it to a very specific portion of hardware containing RAM, CPU, Network or Hard Drive.</p><p>Now, if container is that, then what is an image and how can an image ie file create a running container? Anytime we talk about an image, we talk about a file system snapshot or a copy-paste of a very specific set of <strong>directories and files</strong> plus a <strong>startup command</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*9ejmUSfbB-PPyzOFV47Oug.png" /><figcaption>Docker Image</figcaption></figure><p>Thus, while creating a container out of an image, the file system snapshot of the image is <strong>copied</strong> into the <strong>hard disk</strong> of the <strong>container</strong> and the startup command is <strong>run</strong> on the container with the required set of hardware and software resources.</p><p>The concepts <strong>namespacing </strong>and <strong>control group </strong>are exclusive to linux operating system. Thus, when one installs and runs docker, one has a LVM (Linux Virtual Machine) running on the computer. This LVM acts as a layer or interface between your actual operating system and kernel. To verify that one has an LVM running, one can type on terminal the following</p><p><strong>docker version</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syCFhmR9umbxzfsNktwe8w.png" /></figure><p>Once can see that the value against the key <strong>OS/Arch</strong> is <strong>linux/amd64 </strong>irrespective of the operating system.</p><h3>Summary</h3><p>This post describes the 101 of docker, images and containers. We went through what the basic need of using a docker container is, how an operating system manages the relationship between application software and hardware, need for dependency management, the concepts of namespacing and control-group, how a docker container solves the overall problem and finally what exactly is a docker image and a docker container.</p><p>Special thanks to <a href="https://medium.com/u/d058882d8cd2">Stephen Grider</a> and his udemy course on Docker and Kubernetes, which helped me clear these concepts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6970649ef639" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Testing in Node.js]]></title>
            <link>https://javascript.plainenglish.io/automated-testing-in-node-js-2aa306d091?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa306d091</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sat, 15 May 2021 12:56:27 GMT</pubDate>
            <atom:updated>2021-05-17T20:08:01.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yowTcpRtP_ic6q3Eh87koA.png" /><figcaption>Node.js libraries Jest and Puppeteer</figcaption></figure><p>A very important aspect of software development lifecycle is assuring the quality of the software. One might write the best code, with full concentration, with the most optimised algorithm, still one cannot be immune to the bugs which prop up in any software.</p><p>There can be two broad approaches to testing.</p><p>The first approach can be to test the feature in one’s product manually for all the test cases.</p><p>The other approach would be to write automated test cases.</p><p>The benefit in the latter approach is that when one changes something in the code, one can run test cases instantly, get errors if the new code breaks something and one does not need to manually check all test cases again. It saves time.</p><p>Writing automated test cases also helps us to think about possible issues and edge cases. Thus, it is considered a good practice to write test cases in code.</p><p>Automated tests in Node.js can be classified into three types:</p><ul><li><strong>Unit Tests</strong> : Test an isolated function.</li><li><strong>Integrated Tests</strong> : Tests a function that calls another function.</li><li><strong>End to end tests</strong> : Tests in an automated way what can be done manually from the user interface of a browser or app.</li></ul><p>Unit tests are the simplest to write and are written quite extensively. End to end tests are complex thus sparingly written. Integrated tests come in the middle in terms of complexity and frequency of writing.</p><p>Testing Setup can be classified into three levels:</p><ul><li><strong>Test Runner : </strong>Executes your tests and summarises your results. e.g. Mocha</li><li><strong>Assertion Library : </strong>Defines testing logic, conditions. e.g. Chai</li><li><strong>Headless browser : </strong>Simulates browser interactions. e.g. Puppeteer</li></ul><p>However, there is an npm package which performs the role of <strong>Test Runner </strong>as well as <strong>Assertion Library</strong>. That npm package is <strong>jest</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6096c953c21b80001482fe5e&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fdeclares-the-test-runner-and-assertion-library-as-jest-jest-nodejs-testing%2F6096c953c21b80001482fe5e&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fget-on-firefox.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8d56d41c5563e9bfd3ff0be44506335/href">https://medium.com/media/f8d56d41c5563e9bfd3ff0be44506335/href</a></iframe><p>Use the above snippet inside package.json to include jest as the testing library and add jest to the list of dev dependencies using <strong>npm i jest — save-dev</strong></p><p>Now, one can create a file ending with *<strong>.test.js </strong>in which one can define all the tests to be executed on the outputs of every function which one wants to test. Let’s analyse the code snippet inside the *.test.js file.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6096d19dc21b80001482fe5f&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fsample-unit-test-jest-nodejs-testing%2F6096d19dc21b80001482fe5f&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fsave-snippets-vs-code.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="153" frameborder="0" scrolling="no"><a href="https://medium.com/media/764a2d2e4fe24c556bcc48d1afdd8b26/href">https://medium.com/media/764a2d2e4fe24c556bcc48d1afdd8b26/href</a></iframe><p>Assume <strong>getIntroduction</strong> to be a function which returns a string describing how old is a particular person. It takes two arguments, first a string defining the name of the person and second a number defining the age of the person.</p><p><strong>test </strong>is defined by the same name. First argument is the name of the test case in the form of string. Second argument is an anonymous function containing the assertion over the result of getIntroduction function. <strong>expect </strong>is the keyword for defining an assertion.</p><p>If the output of the function is as expected the <strong>npm run test</strong> would show PASS and if the output of the function is not as expected <strong>npm run test</strong> would show FAILED.</p><p><strong>End to End tests: </strong>For performing end to end UI tests, we would use the npm package called <strong>puppeteer</strong>. Installing it is quite simple, just do <br>npm i — save puppeteer</p><p>puppeteer would help us simulate the browser, allow us to specify the dimensions of the browser screen, allow us to adjust the speed of the actions performed on the browser and allow us to specify if we want to launch the browser in a headless way or in a full fledged way.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F609fa77ef0c8580014c813f2&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fperforms-e2e-testing-using-puppeteer-jest-nodejs-testing-puppeteer%2F609fa77ef0c8580014c813f2&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fget-on-firefox.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/18c7abdf65207d0cf8e7a7993391f4e3/href">https://medium.com/media/18c7abdf65207d0cf8e7a7993391f4e3/href</a></iframe><p>First we initialise the browser with puppeteer.launch method. It launches the chromium browser. One sees this message below the address bar in the chrome browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*6jcCD3Uk3b3id77CZDGyfA.png" /></figure><p>Inside the launch method, we have a key called <strong>headless </strong>that specifies whether we want to launch the browser as headless ie without opening the browser window or not. <strong>slowMo </strong>specifies at what rate would the testing be performed. A higher number means that the rate of operations ie click, typing etc would be slower. In the <strong>args, </strong>one can specify the window size of the browser on which testing would be performed.</p><p>Once the browser is launched, a new page or tab is opened using <strong>browser.newPage()</strong>. Then to specify the url which should open on this tab or page, one can call the <strong>goto(url) </strong>method of the page. Each function call starts with the <strong>await </strong>keyword signifying that each browser operation is an asynchronous operation in itself.</p><p>Next comes the part where we specify the actions which will be automated in the E2E testing. One can simulate a click action <strong>page.click(‘valid html element selector’) </strong>or simulate typing of text by <strong>page.type(‘valid html element selector’, text) </strong>where text contains the string which we want to fill in the text box, input element or any writable html element matching our <strong>html selector</strong>.</p><p>Thus, await page.type(‘input.input-text’, ‘Hello World!’)<em> </em>would find the html <strong>&lt;input&gt;</strong> element with class <strong>‘input-text’ </strong>and simulate the typing of the string ‘Hello World’ there. Similarly, await page.click(‘#search-btn’) would simulate the click on html element with id search-btn.</p><p>Now comes the part to validate the output of our automated actions. To validate them, one can use <strong>$eval </strong>method on page. To give an example,</p><p>const finalText = await page.$eval(‘.input-text’, el =&gt; el.textContent)</p><p>finalText variable would store the text value inside the html element with class ‘input-text’. element.textContent does the job of taking out the text content from a div. Sometimes, _value key is used to extract the text content from an html element.</p><p>Next task is simple to pass this value to jest assertion ie <br>expect(finalText).toBe(‘Hello World!’). Thus, our action gets validated</p><p>A successful test run would look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rCIx2NJSaQNJZnFW5hArg.png" /><figcaption>Command line output for a successful run of test cases</figcaption></figure><p>The role of automated testing in the software development lifecycle cannot be emphasised less. One should not fall for the opinion that writing test cases is doing a trivial and mundane job and it delays the product development. However, most experienced developers suggest that writing test cases including unit tests and E2E tests not only reduces the possible bugs in the code but also reduce the iterations for fixes and over time save the developer’s time and effort.</p><p>To sum up, there are three things which make a software bug free: Testing, more testing, and even more testing!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa306d091" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/automated-testing-in-node-js-2aa306d091">Automated Testing in Node.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Upload and Download in Node.js]]></title>
            <link>https://medium.com/geekculture/file-upload-and-download-in-node-js-c524a8050c8f?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c524a8050c8f</guid>
            <category><![CDATA[download]]></category>
            <category><![CDATA[filé]]></category>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[upload]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 10:22:44 GMT</pubDate>
            <atom:updated>2021-04-05T22:34:12.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>File Upload and Download in Node.js using Multer</h3><p>Uploading or downloading files in your application is not something which you would use very rarely. Thus, it is important to know how to upload files at the client-side and how to handle and store files at the server-side. Also, while fetching the file stored at the server, one has to be aware of the different possibilities like should the downloaded file open in one of the browser tabs or it should be downloaded as an attachment and opened separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rc78D8gjIIvova2pdTst8A.png" /></figure><h4>File upload at the client side:</h4><p>For explaining the file upload at the client side, code snippet of Vue.js has been used as an example below. Inside the form element, <strong>enctype=</strong><strong>&quot;multipart/form-data&quot; </strong>signifies that what is submitted through the form is not just text but also files. If one wants to submit only text in the form, one should use <strong>enctype=</strong><strong>&quot;</strong><a href="http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm"><strong>x-www-urlencoded</strong></a><strong>&quot;</strong> as that would be efficient.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6062b9dd92bf3000148bfb74&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fupload-files-html-vue-js%2F6062b9dd92bf3000148bfb74&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fget-on-firefox.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="153" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1bf2cc072731a34dd9ed4e7066560da/href">https://medium.com/media/b1bf2cc072731a34dd9ed4e7066560da/href</a></iframe><p>The input element has a type of <strong>&quot;file&quot;</strong> which represents that this input element does not take text input but instead a file explorer opens up on clicking the input box corresponding to the input element. When you select a file from the explorer and click <strong>Open</strong>, then <strong>@change</strong> hook gets triggered and it calls the attached functions and statements. Here, the attached function filesChange takes two arguments, <strong>name of element </strong>and <strong>list of files</strong>. <strong>Name of input element </strong>for the case of above input element would be <strong>&quot;photo&quot;</strong>, as that has been passed as name=<strong>&quot;photo&quot;</strong> in the input element. <strong>List of files</strong> would represent an array which contains all the files which one had selected in the file explorer.</p><p>Now coming to the method <strong>filesChange, </strong>we create a JS object called <strong>FormData</strong>. FormData is an iterable object which replicates forms. It can be seen as an array of arrays. Each one array would represent the elements which one wants to send to the server. Each one array has a name and a value. One optional param is fileName. These are added by the <strong>.append(name, value, ?fileName) </strong>method to formData. Name represents the name of the input element and value either represents a string or a BLOB (Binary Large Object) and fileName is the name of the file with which it would be received on the server.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6062bc3292bf3000148bfb75&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fcreates-a-formdata-object-and-sends-that-to-server-in-a-post-request-vue-js-javascript%2F6062bc3292bf3000148bfb75&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fsave-snippets-vs-code.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="491" frameborder="0" scrolling="no"><a href="https://medium.com/media/d86eec2d8497e45ef9025b8b7f55ab9f/href">https://medium.com/media/d86eec2d8497e45ef9025b8b7f55ab9f/href</a></iframe><p>Now, the next task is to post the uploaded file to the server where it would be handled appropriately. We use <strong>axios </strong>which is an http client and can be used to send http requests. Here, we use <strong>axios.post(url, formData) </strong>method since we are adding something thus HTTP verb POST. We need a backend server running so that the file which we are sending from the client side is handled properly at the server.</p><p><strong>File handling at the backend side:<br></strong>We have used Express server at the server side. At the backend stage, one has to map the routes with appropriate controller functions. The route in our case is ‘/upload’. We will touch upon a node.js library called <strong>multer</strong>. We use multer to extract incoming files. Multer is a middle-ware and extracts the uploaded file from HTTP request</p><p>One can install multer by</p><blockquote>npm install multer — save</blockquote><p>Now we can import multer in our routes file as</p><p>const multer = require(‘multer’)<br>app.use(multer().single(‘photos’))</p><p>Here, app is an instance of <strong>express</strong> object. <strong>.single(name) </strong>specifies that we want only one file to be uploaded for a particular input element name which is ‘photos’ for our case. Now once the <strong>multer </strong>middleware is applied, we can access the file using <strong>req.file</strong>. req.file contains</p><p><strong>fieldname:</strong> input element name against which the file was uploaded<br><strong>originalname:</strong> original name of the file. The name which server uses to store the file can be different from the original name<br><strong>encoding: </strong>number of bits used for encoding<br><strong>mimetype: </strong>which type of file was this<br><strong>buffer: </strong>file was sent to the server as a stream and buffer contains that stream.</p><p>The buffer stream can be converted into binary data if we use <strong>dest</strong> param in multer</p><p>app.use(multer({dest: ‘destinationFolder’}).single(‘photos’))</p><p>The destinationFolder inside the root of our backend project will be the place where the file sent as buffer stream would be stored as a binary object. In that case, we would not see the <strong>buffer </strong>key in the req.file.</p><p>To get more options around how the incoming file would be stored, we can use <strong>.diskStorage </strong>method of multer</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6062be0992bf3000148bfb78&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fparse-the-uploaded-files-specify-their-location-and-filter-a-specific-type-of-files-through-multer-javascript-node-js%2F6062be0992bf3000148bfb78&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fsave-snippets-vs-code.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="465" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e34fa040cc7be283e9bc17bdba87236/href">https://medium.com/media/5e34fa040cc7be283e9bc17bdba87236/href</a></iframe><p><strong>destination</strong> is a function which takes http req variable, file and a cb (callback) as param. The callback in turn takes error (if any, null if no error) as the first param and destination folder as the place where one wants to store the files. Similarly, the filename function also takes http req variable, file and a cb (callback) as params. This callback again takes error (if any, null if no error) as the first param and the name by which we have to store the file as the second param. Here, we have appended timestamp to the file’s original name to prevent any clash arising from repeated uploads of the same file. <br>In the same fashion we can add a file filter which would disallow upload of file which do not match a particular mimetype. In this example, we allow only images of png, jpg and jpeg type.</p><p>Now since we have stored the file in the server file system, the next thing would be to download the file from front-end through another http request</p><p>To download the file, we need to use an inbuilt library of JS called ‘fs’ or file system. It allows us to file system operations. To download the file at a particular path, we just need to put the below code in the right controller.</p><p>const fs = require(&#39;fs&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kLOAASNUZ2eLla_ZMr3Qg.png" /></figure><p>We set ‘Content-Disposition’ header. ‘attachment’ means that the file will not be opened in the browser but it will be downloaded first before opening.<br>The variable <strong>filename</strong> contains the name of the file by which the new file would be downloaded. This would work.</p><p>But here we are reading whole file in one go through <strong>readFile. </strong>For bigger files, it will take long for the file to get downloaded. Worse than that, sometimes the memory on the server might overflow for many incoming requests as it has to read all the data in memory.<br>Thus, to improve it, we must use file stream</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.thiscodeworks.com%2Fembed%2F6062bf0c92bf3000148bfb7b&amp;dntp=1&amp;display_name=thiscodeworks&amp;url=https%3A%2F%2Fwww.thiscodeworks.com%2Fdownload-function-helps-download-a-file-at-a-particular-path-javascript-node-js-express%2F6062bf0c92bf3000148bfb7b&amp;image=https%3A%2F%2Fwww.thiscodeworks.com%2Fimages%2Fsave-snippets-vs-code.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=thiscodeworks" width="620" height="205" frameborder="0" scrolling="no"><a href="https://medium.com/media/05b5dfbc325c60e0b00fed194d7d0e09/href">https://medium.com/media/05b5dfbc325c60e0b00fed194d7d0e09/href</a></iframe><p>In the above piece of code, we first create a file read stream as we want to read data from a specific path. The param <strong>path </strong>contains the relative address of the file to be downloaded in the form of string. Again, we set the ‘Content-Disposition’ header to ‘attachment’ so that the file gets downloaded as an attachment with the name as the variable filename holds. <strong>pipe </strong>method takes a read stream and puts its content into a write stream. Here, http res is a write stream so we write the entire data of readable file stream to http response res. Now try running the code, a file explorer would open and you can specify the folder where you want to store the file. After doing that, the file would be dowloaded and would appear in the bottom of your browser as this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGJC4VaCn4aMWBa6R5BUbg.png" /></figure><p><strong>Summary</strong></p><p>That is it for the blog. We learnt about uploading file from the front-end. At the backend level, we handled file upload through a nice middleware called multer which automatically extracts file and stores them as specified by us. It can filter certain file types for us. We also learnt about how to download files by creating read file streams and using pipe to write that stream to HTTP response. For reference, on can refer to my code in the following git repository</p><p><a href="https://github.com/abhirath14/Upload-Download">abhirath14/Upload-Download</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c524a8050c8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/file-upload-and-download-in-node-js-c524a8050c8f">File Upload and Download in Node.js</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Story of the HDFC bank]]></title>
            <link>https://shubham-sharma75089.medium.com/story-of-the-hdfc-bank-6f16d3ab28b4?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f16d3ab28b4</guid>
            <category><![CDATA[india]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[hdfc-bank]]></category>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[banking]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 12:48:53 GMT</pubDate>
            <atom:updated>2021-02-06T13:05:39.440Z</atom:updated>
            <content:encoded><![CDATA[<p>India’s largest private sector bank by all parameters - the HDFC bank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1v8WhYrURX2zN9gwNF0_Q.jpeg" /><figcaption>Source: Wikipedia</figcaption></figure><p>When Indian economy was changing its course in 1991 and the banking sector was opened up for private players, a new success story was in the making. In the year 1994, a banker Mr. Deepak Parekh was looking to setup a modern private bank in India. In those days, people used to crib about poor customer service at public sector banks, lack of good banking products, too much political interference in distribution of loans etc.</p><p>He approached his fellow banker friend Aditya Puri who was the CEO of Citi bank. Then they made their A-team by hiring some young bankers of Citibank, Bank of America, HSBC etc. Getting bankers of top-notch banks in those times for a new bank was a big deal then. But Mr. Puri was able do that. He believed that public sector banks in India had good network and distribution but no good products. He demanded a free hand in running the bank and Mr Parekh who was the MD, agreed.</p><p>For a new bank to compete in the market, finding its niche was important. HDFC bank was a small bank in the mid 90s. It knew that it won’t be able to compete in the corporate banking sector with the big banks of the time. So it focussed on giving innovative technological solutions of corporates instead of giving loans. It focussed more on transactional and cash management business.</p><p>So HDFC introduced ‘Cheque Settlement System’ by which any cheque of a cooperative bank could be settled immediately in any local branch of HDFC bank. For this service, cooperative banks had to deposit some funds at HDFC bank. This was a very effective method to get deposits without even paying interest on it.</p><p>In the 90s, corporate employees were paid salary through cheques. Then the employees had to deposit cheques in banks and had to wait for the cheque to get cleared. HDFC through its core-banking solution made the cheque system obsolete and enabled corporates to deposit salary directly in their employees accounts without the hassles of cheque. But it was pre-conditioned on opening HDFC accounts for all salary accounts in the companies if they wanted this service from HDFC. This is how it acquired customers and deposits initially at low cost and low interests to pay.</p><p>The CASA (Current account / Savings account) ratio of HDFC bank also began to rise. A higher CASA ratio means that the company is able to acquire deposits at a much lower cost. This is so because there is no interest to be paid on current account and minimal interest on savings account. A lower CASA ratio would mean that more deposits of a bank are in FD or higher interest paying deposit instruments. Thus, the fund acquisition cost reduced dramatically for HDFC compared to its competitors like ICICI.</p><p>Then, in late 1990s, the settlement of shares was electronic but payment was manual. HDFC came up with automatic share settlement. This reduced manual payment work of stock brokers and helped the stock exchanges too. To get this benefit, it was made compulsory for them to open HDFC bank accounts.</p><p>The cash management business of HDFC bank has grown by 35-40% annually. Even in corporate lending, HDFC bank focussed on only blue chip companies for corporate lending and underwent due diligence. From early 2000s, it started focussing on retail banking. It increased its bank branches from 57 in 1999 to 761 in 2008. HDFC was the first bank in India to launch mobile banking. It launched products like Loan against Shares, Loan For IPOs. They extensively partnered with merchants for POS (point of sale) terminals. They were early movers in this sector.</p><p>Even after the 2008 crisis, when other banks were reeling under NPAs, HDFC bank held its ground. This is attributed to HDFC banks due diligence, diversified loans and preference for loans to blue chip companies.</p><p>The IPO of HDFC bank had come in 1995. The share price of HDFC bank has been rising by 26% compounded annual growth.</p><p>To summarise, the key lessons which HDFC bank’s story gives us is:</p><p>1. Do not compete in the segment where there already is too much competition. Find your niche. HDFC did not compete in corporate lending when it was small. It introduced innovative services like Cheque settlement, share fund settlement to acquire deposits.</p><p>2. Take first mover advantage by leveraging on technology. HDFC did it through mobile banking and POS terminals</p><p>3. Manage your risk well. It exercised due diligence and restraint in lending. That is why it did not get trapped in the NPA problem</p><p>Last year only, Mr Aditya Puri retired and hung up his boots. He sold his 95% of hist total stake in HDFC bank for Rs 843 cr.</p><p>At a time when people are so brand conscious and like to flaunt and brag about the foreign brands, Mr. Aditya Puri said last year that he preferred to wear Bata footwear. Recently in his address to shareholders, the bank&#39;s chief recalled his long-standing relationship with the company.</p><p>“We came to start this bank 25 years ago, a bunch of us so-called kids at that time, who had grown up in middle-class backgrounds sharing a coke and wearing Bata shoes,&quot; said Aditya Puri in his address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*JslQhO9gQv_uEfu5KZDssA.jpeg" /><figcaption>Source: Business Today</figcaption></figure><p>HDFC bank’s story is a success story of entrepreneurship, professionalism and corporate governance thriving in post economic reform sun in India. It is a story worth telling.</p><p>Source: Bank for the Buck by Tamal Bandhopadhyay</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f16d3ab28b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strapi: The headless CMS]]></title>
            <link>https://shubham-sharma75089.medium.com/strapi-the-headless-cms-3c0eb85ee045?source=rss-d91bd3e44dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c0eb85ee045</guid>
            <category><![CDATA[strapi]]></category>
            <category><![CDATA[headless-cms]]></category>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[developer-blog]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Shubham Sharma]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 11:23:28 GMT</pubDate>
            <atom:updated>2021-02-01T04:34:36.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine that you are maintaining a large website with tens of pages and a lot of text, images, videos, gifs etc. To embed all this data within the code will not only bloat the size of your code repository but also make your website content difficult to manage. For every change in the content, however small it may be, you would need a developer and it might take time to deploy those changes.</p><p>There comes the concept of a CMS (Content Management System). As the name suggests, a CMS takes responsibility for storing your content in an organised manner and helping you retrieve relevant data for your client side application. CMSs can be broadly classified as either <strong>Traditional </strong>or <strong>Headless</strong>. A good example of a traditional CMS can be <strong>Wordpress </strong>in which the client side and the content management system are tightly coupled. However, such an approach lacks reusability as your CMS would in that case cater to only one type of client application say a react web app and not an angular app or an android app or an iOS app or something else. To achieve reusability, and to separate client side output from the content, one needs the headless approach. In this blog, let’s explore <strong>Strapi: The Open Source &amp; Headless CMS</strong>.</p><h3>Strapi</h3><p>As mentioned before, Strapi is an open source CMS whose code is available on github and hundreds of contributors contribute to it. The content is totally de-coupled from client side application and is stored on a cloud. You can host your strapi server locally also and customise its APIs. All CRUD operations can be performed on the content in the form of REST APIs.</p><h3>Installation</h3><p>Strapi is self-hosted and its installation is fairly simple. One can refer to the official strapi docs for getting started. One can get started with CLI, docker and many more. Link to that is the following:</p><p><a href="https://strapi.io/documentation/developer-docs/latest/getting-started/installation.html#installation-guides">Installation</a></p><h3>Getting Started</h3><p>Once you have setup strapi, you can open localhost:${PORT}/admin. PORT is 1337 by default. It will show a form for you to register yourself and set username, password and email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fDY3pPR1wtIM8IkRlTI0Q.png" /></figure><p>Once that is done, it will show you a nice dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lydnZuB5ogADYoAx3W34RA.png" /><figcaption>Strapi Dashboard</figcaption></figure><p>On the left you can see a sidebar containing sections COLLECTION TYPES, SINGLE TYPES, PLUGINS and GENERAL. The Users collection type is present by default as one admin user got created when you did signup. You can add more users by going into Users collection type and clicking the Add New Users button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAm2s-J8-z2r1-8FjXPSmg.png" /></figure><p>It shows a form with input boxes. Fill in the relevant details. Confirmed flag can be used to distinguish one set of users from another. Let’s say, users who verified their email vs those who did not. Blocked is another flag for users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDuDiW4NNLwRp0iVhPmUMA.png" /></figure><h4>Content-Types Builders</h4><p>Content-Types Builders, gives you the option of creating new collection types, single data types and components. Collection types are used for the kind of data where there are multiple instances of the same schema or structure like Users. On the other hand, Single types are used for the kind of data which would have only one instance like Home page data, menu data etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sB4KcbQ_bvCZnVTa9SkvA.png" /></figure><p>To create a new collection aka table, choose <strong>Create new collection</strong> <strong>type</strong> in the COLLECTION TYPES section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c0eb85ee045" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>