<?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 Chikku George on Medium]]></title>
        <description><![CDATA[Stories by Chikku George on Medium]]></description>
        <link>https://medium.com/@chikku_george?source=rss-64a627979b8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WXllMU6zRJDVj4nE1JJA4w.jpeg</url>
            <title>Stories by Chikku George on Medium</title>
            <link>https://medium.com/@chikku_george?source=rss-64a627979b8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:09:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chikku_george/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[React State Management]]></title>
            <link>https://medium.com/globant/react-state-management-b0c81e0cbbf3?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c81e0cbbf3</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react-state-management]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[react-state]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 08:01:47 GMT</pubDate>
            <atom:updated>2024-02-15T08:01:47.570Z</atom:updated>
            <content:encoded><![CDATA[<h4>REACTJS SERIES</h4><h3>React State Management — using Zustand</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_e4OOiSszPMpyjUD9_BOw.png" /></figure><p>Do you think state and state management are integral parts of your React application? Have you ever struggled with state management and wondered where to look for a simple state management library? Then this article is for you — <em>it will show you how to handle React state using a simple external library called </em><a href="https://docs.pmnd.rs/zustand/getting-started/introduction"><strong><em>Zustand</em></strong></a>.</p><p>Indeed! State and state management have always been important aspects of a React application, which re-renders only when the state changes. A state can contain data or information about a component. As your application grows, managing the state and data flow across components is critical.</p><h3>React State Management</h3><p>You can manage the state of a React application in several ways.</p><ol><li><strong>React Native State Management. </strong>Hooks like <a href="https://react.dev/reference/react/useState">useState</a>, <a href="https://react.dev/reference/react/useReducer">useReducer</a>, <a href="https://react.dev/reference/react/useRef">useRef</a>, <a href="https://react.dev/reference/react/useContext">useContext</a>, and custom hooks support native state management.</li><li><strong>Indirect State Managers. </strong>These are external libraries such as <a href="https://tanstack.com/router/v1/docs/overview">React Router</a> and <a href="https://tanstack.com/query/latest/docs/react/overview">React Query</a>. They are not primarily used to manage the state. Yet, when combined with a native hook, they can handle the state well.</li><li><strong>Direct State Managers. </strong>There are also third-party libraries that are utilized only for state management. <a href="https://redux.js.org/">Redux</a>, <a href="https://docs.pmnd.rs/zustand/getting-started/introduction">Zustand</a>, <a href="https://jotai.org/">Jotai</a>, and <a href="https://valtio.pmnd.rs/docs/introduction/getting-started">Valtio</a> fall into this genre.</li></ol><h3>What is Zustand?</h3><p><a href="https://docs.pmnd.rs/zustand/getting-started/introduction">Zustand</a> is a state management library. It is compact, fast, and scalable. It is a fairly simple system with little boilerplate code. You can use it with less code than Redux and similar libraries for managing React states. It doesn’t rely on a provider. As a result, you don’t have to code as much React logic, which may lessen the things we tend to forget. It works based on simplified <a href="https://legacy.reactjs.org/blog/2014/07/30/flux-actions-and-the-dispatcher.html">flux</a> principles and primarily makes use of <a href="https://legacy.reactjs.org/docs/hooks-intro.html">hooks</a>.</p><p>Why Zustand?</p><ul><li>It is faster than context. It gives you the option to choose a specific state.</li><li>It does state merging by default. Consider updating a single property of an object state, {x:1, y:2}. You can directly set {y:3}. Zustand will merge the data for you. You don’t have to distribute the old state and update properties like {…state, y:3}.</li><li>It is extendable by default. Thus, you can use a variety of middleware types.</li><li>It is less opinionated. You don’t have to stick to one way of doing things. Even though there is a recommended approach, you are not required to adopt it.</li></ul><h3>Zustand vs. Redux</h3><p>As you may know, Redux is the classic state management library that works with React. It is considered the most popular library for managing React states. Hence, comparing their architectural designs is a fitting component of this article. Look at the architecture below to see how Redux works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUUEnrvJJTkKSx-XXdvW_w.png" /><figcaption>Redux Architecture</figcaption></figure><p>First, you have the front-end user interface, as seen in the architecture above. Action creators ensure that the correct action is triggered for every user request. You can think of an action as an event that describes what happened in the application. It can be like clicking a button or performing a search. Dispatchers will assist in sending those actions to the store. Later on, the reducers will decide how to handle the state. The reducer function changes the state by taking the current state and action object. It will return the new state if required, and the updated state modifications will render the UI.</p><p><em>Now comes the exciting part! </em>Take a look at how Zustand works with the architecture given below. You might get excited by its simplified diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5SdovTtjwHe545H6Q2D_A.png" /><figcaption>Zustand Architecture</figcaption></figure><p>You also have the UI component here. When a change request comes in, it is routed to the store. The store will decide how the state should be changed. The UI will be rendered with the updated changes once the store returns a new state. You don’t see any action creators, dispatchers, or reducers here. Instead, Zustand has a feature that lets you subscribe to state changes. This helps keep your UI in sync with your data.</p><blockquote>For developers looking for a simple and lightweight state management solution without the complexity of a larger toolkit like Redux, Zustand is a perfect option.</blockquote><p><em>End of theory. Get your hands dirty now!</em></p><h3>How to use Zustand with ReactJs?</h3><p>Let’s create a React project to show how to manage the states using Zustand. Consider a Library Store application that keeps track of book issues and returns. The steps are listed below.</p><h4>1. Create a React application</h4><p>Create your React application using the below command.</p><pre>npx create-react-app project_name</pre><h4>2. Install Zustand Dependency</h4><p>Go to the project’s directory and install the zustand dependency to manage the React state.</p><pre>npm i zustand</pre><h4>3. Create a store</h4><p>Create a bookstore. You can refer to the below code to create bookStore.js file.</p><pre>import { create } from &quot;zustand&quot;;<br><br>const bookStore = (set, get) =&gt; ({<br>  books: [],<br>  noOfAvailable: 0,<br>  noOfIssued: 0,<br>  addBook: (book) =&gt; {<br>    set((state) =&gt; ({<br>      books: [...state.books, { ...book, status: &quot;available&quot; }],<br>      noOfAvailable: state.noOfAvailable + 1,<br>    }));<br>  },<br>  issueBook: (id) =&gt; {<br>    const books = get().books;<br>    const updatedBooks = books?.map((book) =&gt; {<br>      if (book.id === id) {<br>        return {<br>          ...book,<br>          status: &quot;issued&quot;,<br>        };<br>      } else {<br>        return book;<br>      }<br>    });<br>    set((state) =&gt; ({<br>      books: updatedBooks,<br>      noOfAvailable: state.noOfAvailable - 1,<br>      noOfIssued: state.noOfIssued + 1,<br>    }));<br>  },<br>  returnBook: (id) =&gt; {<br>    const books = get().books;<br>    const updatedBooks = books?.map((book) =&gt; {<br>      if (book.id === id) {<br>        return {<br>          ...book,<br>          status: &quot;available&quot;,<br>        };<br>      } else {<br>        return book;<br>      }<br>    });<br>    set((state) =&gt; ({<br>      books: updatedBooks,<br>      noOfAvailable: state.noOfAvailable + 1,<br>      noOfIssued: state.noOfIssued - 1,<br>    }));<br>  },<br>  reset: () =&gt; {<br>    set({<br>      books: [],<br>      noOfAvailable: 0,<br>      noOfIssued: 0,<br>    });<br>  },<br>});<br><br>const useBookStore = create(bookStore);<br><br>export default useBookStore;</pre><p>Zustand store is a hook, which is why useBookStore is the component name. create is the method used to create the store. The store is the sole source of truth that each component shares. The function set is used to modify the state of a variable or object. The function get is used to access the state inside actions.</p><p>The state object of the library store in the example contains three fields: books, which contains an array of book details such as id, name, and author. The overall number of books in the library is stored in noOfAvailable, while the total number of books that have been issued to users is stored in noOfIssued. The library store offers four methods: The addBook function will add a new book to the array of books, increasing the number of books that are currently available and setting the state of every newly added book to available. The issueBook function will issue a book to the user. The associated book will now have the status issued. There will be an increase in the count of issues and a drop in the count of available. The returnBook function is used to return the issued book to the library. The status of the returned book will change to available, and the count of issued books will drop while the count of available books will increase. Finally, the reset method clears all of the state fields.</p><h4>4. Bind the component with your store</h4><p>Let’s first create entry point App.js file. Refer to the below code.</p><pre>//App.js<br><br>import { useEffect } from &quot;react&quot;;<br>import BookForm from &quot;./components/BookForm&quot;;<br>import BookList from &quot;./components/BookList&quot;;<br>import useBookStore from &quot;./bookStore&quot;;<br>import &quot;./App.css&quot;;<br><br>function App() {<br>  const reset = useBookStore((state) =&gt; state.reset);<br><br>  useEffect(() =&gt; {<br>    reset();<br>  }, [reset]);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h2&gt;My Library Store&lt;/h2&gt;<br>      &lt;BookForm /&gt;<br>      &lt;BookList /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>There are two components in the App.js file: the BookForm and the BookList. Every time the App component mounts, we also use the reset function to remove any state data.</p><p>Create BookForm.js component. Refer to the below code.</p><pre>//BookForm.js<br><br>import { useState } from &quot;react&quot;;<br>import useBookStore from &quot;../bookStore&quot;;<br><br>function BookFom() {<br>  const addBook = useBookStore((state) =&gt; state.addBook);<br>  const [bookDetails, setBookDetails] = useState({});<br><br>  const handleOnChange = (event) =&gt; {<br>    const { name, value } = event.target;<br>    setBookDetails({ ...bookDetails, [name]: value });<br>  };<br><br>  const handleAddBook = () =&gt; {<br>    if (!Object.keys(bookDetails).length)<br>      return alert(&quot;Please enter book details!&quot;);<br>    addBook(bookDetails);<br>  };<br><br>  return (<br>    &lt;div className=&quot;input-div&quot;&gt;<br>      &lt;div className=&quot;input-grp&quot;&gt;<br>        &lt;label&gt;Book ID&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;id&quot; size={50} onChange={handleOnChange} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-grp&quot;&gt;<br>        &lt;label&gt;Book Name&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;name&quot; size={50} onChange={handleOnChange} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-grp&quot;&gt;<br>        &lt;label&gt;Author&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;author&quot; size={50} onChange={handleOnChange} /&gt;<br>      &lt;/div&gt;<br>      &lt;button onClick={handleAddBook} className=&quot;add-btn&quot;&gt;<br>        {&quot; &quot;}<br>        Add{&quot; &quot;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default BookFom;</pre><p>The BookForm component has form fields for entering book details, such as id, name, and author. Additionally, it has an Add button that uses the bookstore’s addBook method to input these book details. The UI with sample book details is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0b70FPKH7oc3BLGk5CMMw.png" /><figcaption>Enter Book Details on the BookForm component</figcaption></figure><p>Create BookList.js component. Refer to the below code.</p><pre>//BookList.js<br><br>import { Fragment } from &quot;react&quot;;<br>import useBookStore from &quot;../bookStore&quot;;<br><br>function BookList() {<br>  const { books, noOfAvailable, noOfIssued, issueBook, returnBook } =<br>    useBookStore((state) =&gt; ({<br>      books: state.books,<br>      noOfAvailable: state.noOfAvailable,<br>      noOfIssued: state.noOfIssued,<br>      issueBook: state.issueBook,<br>      returnBook: state.returnBook,<br>    }));<br><br>  return (<br>    &lt;ul className=&quot;book-list&quot;&gt;<br>      {!!books?.length &amp;&amp; (<br>        &lt;span className=&quot;books-count&quot;&gt;<br>          &lt;h4&gt;Available: {noOfAvailable}&lt;/h4&gt;<br>          &lt;h4&gt;Issued: {noOfIssued}&lt;/h4&gt;<br>        &lt;/span&gt;<br>      )}<br>      {books?.map((book) =&gt; {<br>        return (<br>          &lt;Fragment key={book.id}&gt;<br>            &lt;li className=&quot;list-item&quot;&gt;<br>              &lt;span className=&quot;list-item-book&quot;&gt;<br>                &lt;span&gt;{book.id}&lt;/span&gt;<br>                &lt;span&gt;{book.name}&lt;/span&gt;<br>                &lt;span&gt;{book.author}&lt;/span&gt;<br>              &lt;/span&gt;<br>              &lt;div className=&quot;btn-grp&quot;&gt;<br>                &lt;button<br>                  onClick={() =&gt; issueBook(book.id)}<br>                  className={`issue-btn ${<br>                    book.status === &quot;issued&quot; ? &quot;disabled&quot; : &quot;&quot;<br>                  }`}<br>                  disabled={book.status === &quot;issued&quot;}<br>                &gt;<br>                  {&quot; &quot;}<br>                  Issue{&quot; &quot;}<br>                &lt;/button&gt;<br>                &lt;button<br>                  onClick={() =&gt; returnBook(book.id)}<br>                  className={`return-btn ${<br>                    book.status === &quot;available&quot; ? &quot;disabled&quot; : &quot;&quot;<br>                  }`}<br>                  disabled={book.status === &quot;available&quot;}<br>                &gt;<br>                  {&quot; &quot;}<br>                  Return{&quot; &quot;}<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/li&gt;<br>          &lt;/Fragment&gt;<br>        );<br>      })}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>export default BookList;</pre><p>The BookList component will display all newly added books to the library. It also shows the number of Available and Issued books. Each book record in the list has two buttons: Issue and Return. The UI looks like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzzOO6phLadV07DhRW4j-w.png" /><figcaption>BookList shows all the book details along with Issue and Return buttons</figcaption></figure><p>There are two books available in the UI above, and Issue button is enabled for each book record. Return buttons are disabled and will enable only for issued books.</p><p>When you click the Issue button, the store’s issueBook method is called. The corresponding book ID will be passed and the matching book’s status will set to issued. Then, the associated Issue button is disabled, while the Return button is enabled. You can also see a decrease in the number of Available and an increase in the number of Issued. Please see the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmKsjPTJCcBU-cMeHrj8OQ.png" /><figcaption>BookList with issued books and Return button enabled</figcaption></figure><p>When you click the Return button, the store’s returnBook method is called. The corresponding book ID will be passed and the matching book’s status will set back to available. The associated Return button is disabled, while the Issue button is enabled back. You can also see an increase in the number of Available and a decrease in the number of Issued. Please see the screenshot prior to the above.</p><blockquote>Since the Zustand store is a hook, you can use it anywhere. In contrast to Redux or Redux Toolkit, no <a href="https://legacy.reactjs.org/docs/context.html">context provider</a> is required. Simply select your state, and the component will re-render when the state changes. We must give a selector to the useBookStore to get only the desired slice.</blockquote><p><em>We are not done yet! Zustand has a big advantage:</em> <strong><em>Middlewares</em></strong><em>.</em></p><h3>Zustand Middlewares</h3><p>Zustand can be used with <a href="https://en.wikipedia.org/wiki/Middleware">middleware</a> to add more features to your application. The most widely used Zustand middlewares are listed below.</p><h4>1. Redux DevTools</h4><p><a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd">Redux DevTools</a> are used to debug state changes in the application. It can be used with Zustand as well. Make sure you have Redux DevTools installed as a Chrome extension. Use the below code to integrate it.</p><pre>import { create } from &quot;zustand&quot;;<br>import { devtools } from &quot;zustand/middleware&quot;;<br><br>const bookStore = (set, get) =&gt; ({<br>  books: [],<br>  noOfAvailable: 0,<br>  noOfIssued: 0,<br>  addBook: (book) =&gt; {<br>    set((state) =&gt; ({<br>      books: [...state.books, { ...book, status: &quot;available&quot; }],<br>      noOfAvailable: state.noOfAvailable + 1,<br>    }));<br>  }<br>});<br><br>const useBookStore = create(devtools(bookStore));<br><br>export default useBookStore;</pre><p>To use devtools, import it from zustand/middleware. Then, wrap your store with devtools using the create method.</p><p>Open the Redux DevTools in the web browser and inspect the state, as seen in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tjau7gmPB8xsuMRfF08Ukw.png" /><figcaption>Debugging Zustand states with Redux DevTools</figcaption></figure><h4>2. Persist Middleware</h4><p>Persist middleware enables you to persist state using any type of client storage. The store’s data will remain in storage even if you reload the application. Refer to the below code to add this middleware.</p><pre>import { create } from &quot;zustand&quot;;<br>import { persist, createJSONStorage } from &quot;zustand/middleware&quot;;<br><br>const bookStore = (set, get) =&gt; ({<br>  books: [],<br>  noOfAvailable: 0,<br>  noOfIssued: 0,<br>  addBook: (book) =&gt; {<br>    set((state) =&gt; ({<br>      books: [...state.books, { ...book, status: &quot;available&quot; }],<br>      noOfAvailable: state.noOfAvailable + 1,<br>    }));<br>  }<br>});<br><br>const useBookStore = create(<br>  persist(bookStore, {<br>    name: &quot;books&quot;,<br>    storage: createJSONStorage(() =&gt; sessionStorage),<br>  })<br>);<br><br>export default useBookStore;</pre><p>Import persist from zustand/middleware. Wrap the store with persist inside the create method. The item in the storage can have a name, but it needs to be unique. Additionally, the type of storage can be specified. sessionStorage is referenced in this code. If nothing is specified, localStorage is the default option.</p><p>Open the web browser and look at the session storage to see the saved state, shown in the screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVw9beZHm-3AgIJRF6XnGA.png" /><figcaption>Persisting Zustand store’s data on session storage</figcaption></figure><h3>Summary</h3><p>As we mentioned in this article, state management is critical in React applications. As your application grows, you will have to pick a strong way to manage its state. The Zustand library is an ideal remedy for managing your React state. It is much simpler and has less boilerplate than Redux. You can also explore different state management libraries to find the right one for your application.</p><h3>References</h3><ol><li><a href="https://docs.pmnd.rs/zustand/getting-started/introduction">https://docs.pmnd.rs/zustand/getting-started/introduction</a></li><li><a href="https://www.youtube.com/watch?v=KCr-UNsM3vA">https://www.youtube.com/watch?v=KCr-UNsM3vA</a></li><li><a href="https://www.youtube.com/watch?v=fZPgBnL2x-Q">https://www.youtube.com/watch?v=fZPgBnL2x-Q</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c81e0cbbf3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/react-state-management-b0c81e0cbbf3">React State Management</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VineJS: Validation Library for NodeJs]]></title>
            <link>https://medium.com/globant/vinejs-validation-library-for-nodejs-2521630a8f56?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2521630a8f56</guid>
            <category><![CDATA[form-data-validation]]></category>
            <category><![CDATA[data-validation-libraries]]></category>
            <category><![CDATA[data-validation]]></category>
            <category><![CDATA[vinejs]]></category>
            <category><![CDATA[adonisjs]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 14:10:14 GMT</pubDate>
            <atom:updated>2023-11-24T14:10:14.687Z</atom:updated>
            <content:encoded><![CDATA[<h4>NODEJS SERIES</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRw-T1JfzzIiVhFFTLTXPQ.png" /></figure><p>This article will go through the VineJS data validation library and utilize a NodeJS application to demonstrate how to use it.</p><h3>What is VineJS?</h3><p><a href="https://vinejs.dev/docs/introduction">VineJS</a> is a data validation library that you may use in your NodeJS applications. Its codebase is not brand new, as it is an upgraded version of the previous <a href="https://docs.adonisjs.com/guides/validator/introduction">AdonisJs</a> validator codebase, making it a stand-alone library. It is solely designed for use with the NodeJs runtime in a backend environment. It cannot be run in a browser and is frequently used to validate the HTTP request body that your applications get.</p><p>Why do we need VineJS?</p><ul><li>Many popular validation libraries are also available, such as <a href="https://zod.dev/">Zod</a> and <a href="https://www.npmjs.com/package/yup">Yup</a>. However, VineJS stands out for its quickness. It’s faster than Zod or Yup. You can compare the results of validating a basic object with these libraries <a href="https://vinejs.dev/docs/introduction#benchmarks">here</a>. VineJS is 9 times faster than Zod.</li><li>VineJs will pre-compile your schemas, whereas Zod will not. When you define a schema and use it to execute validation, Zod re-parses the entire schema and performs validations. However, when you create your schema, VineJs compiles it into a Javascript function. This Javascript function has been highly optimized for performance. VineJs will do the validations using these pre-compiled schemas.</li><li>VineJS is only intended to be used for validating JSON payloads or form data that is requested via HTTP requests. Zod, on the other hand, is mostly used to validate all Javascript data types in your projects.</li><li>VineJS has more validation rules than Zod, including database-specific ones.</li><li>VineJS is relatively simple to extend. You can make custom rules and schema types.</li></ul><h3>How do we use VineJS for validation?</h3><p>Let’s create a NodeJs application that will use VineJS as the validation library to validate an HTTP POST request. Set it up by following the steps below.</p><ol><li>Create a <em>package.json</em> file by running the command npm init -y</li><li>Install the dependencies required to set up the server such as express, body-parser</li></ol><pre>npm i express body-parser</pre><p>3. Install VineJS as follows.</p><pre>npm i @vinejs/vine</pre><p>4. Create an <em>index.js </em>file to start the server.</p><pre>import express from &quot;express&quot;;<br><br>const app = express();<br>const port = 8080;<br><br>app.listen(port, async () =&gt; {<br>  console.log(`Server started at port ${port}`);<br>});</pre><p>5. Import VineJS and add the schema validation as given below.</p><pre>import express from &quot;express&quot;;<br>import bodyParser from &quot;body-parser&quot;;<br>import vine, { errors } from &quot;@vinejs/vine&quot;;<br><br>const app = express();<br>const port = 8080;<br><br>const schema = vine.object({<br>  name: vine.string(),<br>  email: vine.string().email(),<br>  password: vine.string().minLength(6).confirmed(),<br>});<br><br>app.use(bodyParser.json());<br><br>app.post(&quot;/&quot;, async (req, res) =&gt; {<br>  const data = req.body;<br>  try {<br>    const validator = vine.compile(schema);<br>    const output = await validator.validate(data);<br>    res.status(200).send(output);<br>  } catch (error) {<br>    if (error instanceof errors.E_VALIDATION_ERROR) {<br>      res.status(error.status).send(error.messages);<br>    }<br>  }<br><br>});<br><br>app.listen(port, async () =&gt; {<br>  console.log(`Server started at port ${port}`);<br>});</pre><p>The VineJS package is exclusive to ESM (<a href="https://nodejs.org/api/esm.html#modules-ecmascript-modules">ECMAScript Modules</a>) and is not compatible with the CommonJS module system. The vine.object method defines the top-level object for the validation schema. vine.compile can pre-compile the given schema. VineJS will pre-compile your schema into an optimized JavaScript function. This optimized function can be later used for further validations. The validate method is used to carry out the validation. The validate method takes a data object as an argument and performs validation on the pre-compiled validator object.</p><p>If validation succeeds, the return value will be a new object with the validated properties. Consider the following data, which has no validation errors. It will return the input object with the validated properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aJlchrwflhB1RWQPHGDjw.png" /><figcaption>Input data without any validation error</figcaption></figure><p>If validation fails, an exception will be thrown. Consider the data below, which has an invalid password field. It will throw an error with the appropriate message and validation rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TR261eDhnTlYrA_rqG2zg.png" /><figcaption>Input data with an invalid password field</figcaption></figure><h3>How to set up custom error message in VineJS</h3><p>VineJS uses a message provider to manage the custom error messages. A message provider selects where to read the messages and how to handle validation errors. The message provider can be specified globally, per schema, or when the validate method is executed.</p><p>The SimpleMessageProvider takes two arguments. The first argument is the messages, which is an object of key-value pairs. The key can be the rule name or the field + rule combination, and the value is the error message. The second argument is an object of input fields. The input field name is substituted for the {{ field }} placeholder in error messages.</p><h4>Configure globally</h4><p>The simple message provider can be globally defined as follows. Such message providers are shared by all validator schemas in our application.</p><pre>import vine, { SimpleMessagesProvider } from &quot;@vinejs/vine&quot;;<br><br>const fields = {<br>  name: &quot;Name&quot;,<br>  email: &quot;Email&quot;,<br>  password: &quot;Password&quot;,<br>};<br><br>vine.messagesProvider = new SimpleMessagesProvider(<br>  {<br>    // Applicable for all fields<br>    required: &quot;The {{ field }} field is required&quot;,<br>    string: &quot;The value of {{ field }} field must be a string&quot;,<br>    email: &quot;The value is not a valid email address&quot;,<br><br>    // Error message for the custom fields<br>    &quot;name.required&quot;: &quot;Please enter name&quot;,<br>    &quot;email.required&quot;: &quot;Please enter email&quot;,<br>    &quot;password.required&quot;: &quot;Please enter password&quot;,<br>  },<br>  fields<br>);</pre><h4>Per schema level</h4><p>We can define the default message provider at the schema level to ensure that it is available only for that particular schema. Once your schema has been pre-compiled, you can define the message provider on the optimized validator object that you receive.</p><pre>import vine, { SimpleMessagesProvider } from &quot;@vinejs/vine&quot;;<br><br>const fields = {<br>  name: &quot;Name&quot;,<br>  email: &quot;Email&quot;,<br>  password: &quot;Password&quot;,<br>};<br><br>const messagesProvider = new SimpleMessagesProvider(<br>  {<br>    // Applicable for all fields<br>    required: &quot;The {{ field }} field is required&quot;,<br>    string: &quot;The value of {{ field }} field must be a string&quot;,<br>    email: &quot;The value is not a valid email address&quot;,<br><br>    // Error message for the custom fields<br>    &quot;name.required&quot;: &quot;Please enter name&quot;,<br>    &quot;email.required&quot;: &quot;Please enter email&quot;,<br>    &quot;password.required&quot;: &quot;Please enter password&quot;,<br>  },<br>  fields<br>);<br><br>const schema = vine.object({<br>  name: vine.string(),<br>  email: vine.string().email(),<br>  password: vine.string().minLength(6),<br>});<br><br>const validator = vine.compile(schema);<br>validator.messagesProvider = messagesProvider;</pre><h4>On validation call</h4><p>During the validation call, the message provider can also be defined. By using the validate method, the data is validated against a schema. You have the option to share the message provider with the validator in the manner described below.</p><pre>import vine, { SimpleMessagesProvider } from &quot;@vinejs/vine&quot;;<br><br>const fields = {<br>  name: &quot;Name&quot;,<br>  email: &quot;Email&quot;,<br>  password: &quot;Password&quot;,<br>};<br><br>const messagesProvider = new SimpleMessagesProvider(<br>  {<br>    // Applicable for all fields<br>    required: &quot;The {{ field }} field is required&quot;,<br>    string: &quot;The value of {{ field }} field must be a string&quot;,<br>    email: &quot;The value is not a valid email address&quot;,<br><br>    // Error message for the custom fields<br>    &quot;name.required&quot;: &quot;Please enter name&quot;,<br>    &quot;email.required&quot;: &quot;Please enter email&quot;,<br>    &quot;password.required&quot;: &quot;Please enter password&quot;,<br>  },<br>  fields<br>);<br><br>const schema = vine.object({<br>  name: vine.string(),<br>  email: vine.string().email(),<br>  password: vine.string().minLength(6),<br>});<br><br>const validator = vine.compile(schema);<br>validator.validate(data, { messagesProvider: messagesProvider });</pre><h3>Summary</h3><p>We just demonstrated how to use the VineJS library to validate the HTTP request content in Node.js applications in this article. VineJS stands out amid other validation libraries, such as Yup and Zod. We have only examined a sample validation schema and the validation process in this post. You can go into greater detail on your own by referring <a href="https://vinejs.dev/docs/introduction">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2521630a8f56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/vinejs-validation-library-for-nodejs-2521630a8f56">VineJS: Validation Library for NodeJs</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Optimization in ReactJs]]></title>
            <link>https://medium.com/globant/performance-optimization-in-reactjs-26be40a21a96?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/26be40a21a96</guid>
            <category><![CDATA[throttling]]></category>
            <category><![CDATA[react-optimization]]></category>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[debouncing]]></category>
            <category><![CDATA[usecallback]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 13:57:18 GMT</pubDate>
            <atom:updated>2023-07-12T13:57:18.707Z</atom:updated>
            <content:encoded><![CDATA[<h4>REACTJS SERIES</h4><h4>A guide to ReactJs performance optimization strategies, with scenarios, explained</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*umdY5_ua4Kg2f6ol.png" /><figcaption>Credit: <a href="https://blog.francium.tech/react-js-advance-guide-cheat-sheet-403cf7ff6f82">Francium Tech</a></figcaption></figure><p>As a developer, the performance of an application is always critical as it might affect the user experience on your website. Multiple studies and research proved that a website’s performance might impact conversion rates and sales. According to <a href="https://www.portent.com/blog/analytics/research-site-speed-hurting-everyones-revenue.htm#:~:text=The%20first%205%20seconds%20of,(between%20seconds%200%2D5)">Portend</a> study, a website’s conversion rate is five times higher when it loads in one second compared to 10 seconds. As a result, developers should prioritize performance optimization to improve user experience. The application should keep users engaged.</p><p>React applications generally deliver a very fast user interface via <a href="https://legacy.reactjs.org/docs/faq-internals.html">Virtual DOM</a>. However, when the application expands, performance problems may arise. As part of this article, we will see a few scenarios and discuss how we may use optimization strategies to boost performance.</p><h3>Optimization Techniques</h3><p>Below are the optimization techniques which are going to explain in detail.</p><ol><li>Code Splitting &amp; Lazy Loading</li><li>Debouncing</li><li>Throttling</li><li>Memo</li><li>useCallback</li><li>useMemo</li></ol><h3>Code Splitting &amp; Lazy Loading</h3><p>In essence, React application merges every file into a single bundle. This bundle is used on a webpage to load a whole application at once. If the application is small-scale, it might not impact the performance. However, the bundle also grows in size as the program does. So you must ensure that the code provided in the bundle does not make it too huge so that the application can load faster.</p><p>To avoid large bundles, you can split the bundles through a process called <a href="https://legacy.reactjs.org/docs/code-splitting.html">Code Splitting</a>. Bundlers such as <a href="https://webpack.js.org/concepts/">Webpack</a>, <a href="https://rollupjs.org/">Rollup</a>, and <a href="https://browserify.org/">Browserify</a> provide Code Splitting. Code Splitting allows distinct bundles to be dynamically loaded at runtime. Code Splitting enables lazy loading of the user’s present needs. Using <a href="https://react.dev/reference/react/lazy">Lazy Loading</a>, you can speed up initial load times by loading parts of your application as needed. In cases where you know the user does not commonly access a specific code, it is ideal to load it when the user asks for it. Both the user experience and the initial loading time are enhanced by this.</p><p>Consider a scenario where your React application contains a home and an admin page. The home page will have a link to the admin page. Typically, a React application loads all of its components at once. All the loaded code is visible in the source directory under developer tools. The below image depicts the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SS9NIcVXA3-Z3IMxTaO8Q.png" /><figcaption>All components load at once in the source directory</figcaption></figure><p>In this scenario, not all users have access to the admin page. Only admin users have access to the admin page. As a result, you don’t need to load the admin component at first. You can divide the code and load the admin page only when the user demands it. Add the below code to lazily load the admin page.</p><pre>import { lazy } from &quot;react&quot;;<br>import { BrowserRouter, Route, Routes } from &quot;react-router-dom&quot;;<br>import Home from &quot;./Home&quot;;<br>import &quot;./App.css&quot;;<br><br>const Admin = lazy(() =&gt; import(&quot;./Admin&quot;));<br><br>function App() {<br>  return (<br>    &lt;BrowserRouter&gt;<br>      &lt;Routes&gt;<br>        &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>        &lt;Route path=&quot;/admin&quot; element={&lt;Admin /&gt;} /&gt;<br>      &lt;/Routes&gt;<br>    &lt;/BrowserRouter&gt;<br>  );<br>}<br><br>export default App;</pre><p>When the admin page is lazily loaded, you can see in the source directory that the admin component (admin.js) is not loaded at first. Thus, the initial load time is reduced. The below image depicts the lazy loading of components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qI2p8Ht8X-tQoMcrGabGAA.png" /><figcaption>Admin component didn’t load in the source directory</figcaption></figure><p>The admin page only loads when you click the Go to Admin link. The below image depicts the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSoKI9LqX6Jqrs4_LVPMBA.png" /><figcaption>Admin component loads only when the user clicks the Go to Admin link</figcaption></figure><h3>Debouncing</h3><p>In Javascript, <em>debouncing</em> is a technique used to limit a frequent function call by delaying the execution of the function until a predetermined time. The function will be called only once per use-case to minimize extra CPU cycles and API calls, which improves performance.</p><p>A debounce function can be thought of as a higher-order function that accepts a function and a timer as input arguments and outputs another function. Debounce will set aside a scope for the timer variable and plan the timing for when your function will be called. The debounce function is frequently used for text-field autosaves, search box recommendations, and preventing double button clicks.</p><p>Imagine a situation where you want to display search query suggestions. When the result is displayed while the user is typing, it can result in a significant number of API calls which is not the recommended approach. The graphic below depicts the search API calls made by a user while typing. As the user types each alphabet, the API is continuously called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQMQuox211Mxy5CWXMebFQ.png" /><figcaption>Continuous search API calls while the user types the search query “birds”</figcaption></figure><p>The above approach can be optimized by showing the suggestions only after the user has finished typing. A sample implementation of the debounce function in search is shown in the code below. The debounce method is triggered whenever the user types a letter. Each invocation resets the timer or cancels prior plans with handleChange() and reschedules it for a new time of 500 ms in the future. This will continue as long as the user keeps writing in under 500 ms. The handleChange()function will eventually be called because the last schedule won’t be cleared.</p><pre>import { useState } from &quot;react&quot;;<br><br>function SearchField() {<br>  const [searchItems, setSearchItems] = useState([]);<br><br>  function debounce(func, timeout = 500) {<br>    let timer;<br>    return (...args) =&gt; {<br>      if (timer) clearTimeout(timer);<br>      timer = setTimeout(() =&gt; {<br>        func.apply(this, args);<br>      }, timeout);<br>    };<br>  }<br><br>  function handleChange(e) {<br>    const { value } = e.target;<br>    fetch(`https://demo.dataverse.org/api/search?q=${value}`)<br>      .then((res) =&gt; res.json())<br>      .then((json) =&gt; setSearchItems(json.data.items));<br>  }<br><br>  const optimisedSearch = debounce(handleChange);<br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Enter text here...&quot;<br>        onChange={optimisedSearch}<br>        className=&quot;search&quot;<br>      /&gt;<br>      {searchItems?.length &gt; 0 &amp;&amp; (<br>        &lt;div className=&quot;autocomplete&quot;&gt;<br>          {searchItems?.map((item, index) =&gt; {<br>            return (<br>              &lt;div key={index} className=&quot;autocomplete-items&quot;&gt;<br>                &lt;span&gt;{item.name}&lt;/span&gt;<br>              &lt;/div&gt;<br>            );<br>          })}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>}<br><br>export default SearchField;</pre><p>The graphic below displays the optimized API request, which is only made after the user has finished typing. Debouncing significantly reduces the number of API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCmI97oFrgDtmvr9Mliixg.png" /><figcaption>Optimized search API call by using debouncing</figcaption></figure><h3>Throttling</h3><p>In Javascript, <em>throttling</em> limits how frequently a function may be called in a certain amount of time. A function is not allowed to run again for a predetermined amount of time after it has recently been called. Throttle ensures that a function is invoked at a consistent rate. When an application performs a time-consuming computation or an API request in the event handler callback function, throttling the callbacks prevents the app from lagging or overwhelming your server with requests.</p><p><a href="https://medium.com/stackanatomy/forever-functional-18-debouncing-and-throttling-for-performance-cf2db1bf58f7">Throttling and debouncing</a> are comparable since both are used to enhance a web application’s performance. When you are concerned about the result, use debouncing. For instance, search results once the user has finished typing. On the other hand, throttling controls the rate at which each stage of the operation is carried out. For instance, keeping note of the scrolling offsets that occur as a user scrolls across a web application.</p><p>Think of a situation where an event listener tracks the mouse’s movement and performs actions based on location. Find the code for the usual way to handle this situation below.</p><pre>function handleMouseMove() {<br>    console.log(&quot;api call to do some actions&quot;);<br>}<br>window.addEventListener(&quot;mousemove&quot;, handleMouseMove);</pre><p>In this solution, you will have hundreds of requests in a short period as API calls will be triggered on each mouse movement. The below graphic shows the number of API calls in a short duration of mouse movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*cVdA8Kqh7LogeViRNIkXLQ.gif" /><figcaption>Continuous API calls on mouse movement</figcaption></figure><p>In this scenario, you can use the throttle function to limit the amount of API calls. The throttle function takes two inputs: a function to throttle and a delay of the throttling interval in milliseconds, and returns a throttled function. The throttle function is illustrated in the code below.</p><pre>function throttle(callback, timeout = 1000) {<br>    let shouldWait = false;<br><br>    return (...args) =&gt; {<br>      if (shouldWait) return;<br><br>      callback(...args);<br>      shouldWait = true;<br><br>      setTimeout(() =&gt; {<br>        shouldWait = false;<br>      }, timeout);<br>    };<br>}<br><br>function handleMouseMove() {<br>   console.log(&quot;api call to do some actions&quot;);<br>}<br>window.addEventListener(&quot;mousemove&quot;, throttle(handleMouseMove));</pre><p>As shown in the figure below, employing the throttle function significantly reduces the amount of API calls made for mouse moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DYdE_N2UxZEgnxq9NBAS7g.gif" /><figcaption>Reduced number of API calls on mouse move after throttling</figcaption></figure><h3>React Memo</h3><p><a href="https://react.dev/reference/react/memo">React memo</a> is used to wrap a component to obtain the memoized version of that component. When the props remain intact, it will skip the component’s re-rendering. In reality, React memo compares the new props with the old ones. It uses the previous render if they are equivalent. It re-renders the component if the props are different. React memo only compares props shallowly, which must be considered when sending methods and objects as props. React re-renders a component whenever its parent re-renders. You may use memoto create a component that does not re-render when its parent does, as long as its new props are the same as the old props. Wrap a component in memo to memoize it, then use the value it produces in place of the original component.</p><pre>const MemoizedComponent = memo(SomeComponent, arePropsEqual?)</pre><p>There are two input parameters for React Memo.</p><ul><li>The first is the memo component. Memoizing does not alter this component, instead returns a new, memoized component.</li><li>The second parameter is a function that takes two arguments: the component’s previous and new props. If the old and new props are equivalent, it should return true. If not, it ought to return false. You won’t often define this function as React compares each prop by default. When its state or context changes, a component will still re-render even if it has been memoized. Memoization is limited to props supplied to the component from its parent.</li></ul><p>Consider the rendering of parent and child components as an example. The child component re-renders whenever the parent does. Even if the child component is unaffected by the count state variable, the example shows that anytime we click the count button in the parent component, the child component likewise re-renders. Find the below code for Parent.js and Child.js<em> </em>respectively<em>.</em></p><pre>//Parent.js<br><br>import { useState } from &quot;react&quot;;<br>import Child, { MemoizedChild } from &quot;./Child&quot;;<br><br>function Parent() {<br>  const [count, setCount] = useState(0);<br>  console.log(&quot;Parent renders&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setCount((prev) =&gt; prev + 1)}&gt;<br>        Count - {count}<br>      &lt;/button&gt;<br>      &lt;Child /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default Parent;</pre><pre>//Child.js<br><br>function Child() {<br>  console.log(&quot;Child renders&quot;);<br>  return &lt;div&gt;Child Renders&lt;/div&gt;;<br>}<br><br>export default Child;</pre><p>The image below shows that even though the child component is unaffected by the props, it re-renders with the parent component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJ--If5rA4k-T2G2CdBrnw.gif" /><figcaption>The child component re-renders with the parent component</figcaption></figure><p>It is evident that the above re-rendering of the child component is unnecessary, and these superfluous re-renders can impact performance. To improve this rendering behavior, react should only re-render the component when its props change, and this is done using React memo. The needed changes are reflected in the code below.</p><pre>//Parent.js<br><br>import { useState } from &quot;react&quot;;<br>import Child, { MemoizedChild } from &quot;./Child&quot;;<br><br>function Parent() {<br>  const [count, setCount] = useState(0);<br>  console.log(&quot;Parent renders&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setCount((prev) =&gt; prev + 1)}&gt;<br>        Count - {count}<br>      &lt;/button&gt;<br>      &lt;MemoizedChild /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default Parent;</pre><pre>//Child.js<br><br>import { memo } from &quot;react&quot;;<br><br>function Child() {<br>  console.log(&quot;Child renders&quot;);<br>  return &lt;div&gt;Child Renders&lt;/div&gt;;<br>}<br><br>export const MemoizedChild = memo(Child);<br>export default Child;</pre><p>The optimized behavior with memoizing can be seen in the figure below. As long as the props are unchanged, the child component is not re-rendered with the parent component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_fuWx0HdJUrKL7Ygq4tlQ.gif" /><figcaption>React memo prevents unnecessary re-renderings of the child component</figcaption></figure><h3>useCallback</h3><p><a href="https://react.dev/reference/react/useCallback">u</a>seCallback is a hook that is used to cache a function definition between re-renders. Utilizing the useCallback hook, we may cache functions that are passed to child components as props to enhance rendering performance.</p><pre>const cachedFn = useCallback(fn, dependencies)</pre><p>The hook requires two arguments:</p><ul><li>The function definition is the first one. During the initial render, React will return this function. If the dependencies have not changed since the last render, React will provide the same function to you again on subsequent renders. In the absence of that, it will return the function you gave during the current render and keep it in case it has to be used again.</li><li>The second argument is a list of dependencies that includes each value from your component that is utilized inside of your method.</li></ul><p>Think of a parent and child component example where the parent has a count state that is updated by an increment button. Additionally, the parent component has a handleChange() function that is supplied as a prop to the child component. The child component is wrapped by memo, therefore it should not be re-rendered if its props do not change. Find the code for the same below.</p><pre>//Parent.js<br><br>import { useState } from &quot;react&quot;;<br>import Child from &quot;./Child&quot;;<br><br>function Parent() {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  const handleChange = (value) =&gt; {<br>    setText(value);<br>  };<br>  console.log(&quot;Parent Re-renders&quot;);<br>  return (<br>    &lt;div className=&quot;parent-wrapper&quot;&gt;<br>      &lt;Child onChange={handleChange} /&gt;<br>      Count: {count}<br>      &lt;br /&gt;<br>      &lt;button className=&quot;button&quot; onClick={() =&gt; setCount((prev) =&gt; prev + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default Parent;</pre><pre>//Child.js<br><br>import { memo, useContext } from &quot;react&quot;;<br><br>function Child({ onChange }) {<br>  console.log(`Child Re-renders`);<br>  return &lt;&gt;&lt;/&gt;;<br>}<br>export default memo(Child);</pre><p>The child component is re-rendered each time the increment button in the parent component is clicked, as shown in the graphic below. In React, functions are, by default, recreated with each render. Every render will have a different handleChange() function, which will result in the child component being re-rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eb3sJ9LPbMDF59z4-2_vLg.gif" /><figcaption>The child is unnecessarily re-rendering with the parent</figcaption></figure><p>Large applications can become sluggish as a result of these unwanted re-renderings. You can encase the handleChange() method with the useCallback hook to prevent this. This will cause handleChange() to return a memoized function, which will be the same as the previous one unless the dependency array changes. Thus, you have control over any unintentional re-renderings of your components. Refer to the updated code for Parent.js<em> </em>below.</p><pre>import { useCallback, useState } from &quot;react&quot;;<br>import Child from &quot;./Child&quot;;<br><br>function Parent() {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  const handleChange = useCallback((value) =&gt; {<br>    setText(value);<br>  }, []);<br><br>  console.log(&quot;Parent re-renders&quot;);<br>  return (<br>    &lt;div className=&quot;parent-wrapper&quot;&gt;<br>      &lt;Child onChange={handleChange} /&gt;<br>      Count: {count}<br>      &lt;br /&gt;<br>      &lt;button className=&quot;button&quot; onClick={() =&gt; setCount((prev) =&gt; prev + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default Parent;</pre><p>The graphic below demonstrates how the useCallback hook is properly used to re-render the child component. You can see that the child is not re-rendered along with the parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvY_mJINtAVvPlJU2cCU6A.gif" /><figcaption>The child is not re-rendering after using useCallback</figcaption></figure><h3>useMemo</h3><p>The <a href="https://react.dev/reference/react/useMemo">u</a>seMemo React hook is used to cache a calculation’s outcome between re-renders.</p><pre>const cachedValue = useMemo(calculateValue, dependencies)</pre><p>It requires two parameters:</p><ul><li>The first parameter is the function computing the value you want to cache. It should be a pure function that doesn’t accept any inputs and returns a value of any type. React will call this function during the first render. If the dependencies have not changed since the last render, React will return the same result. If not, it will call this function, return its outcome, and store it for later use.</li><li>The second parameter is a list of dependencies that includes each value from each component used in your calculation.</li></ul><p>Consider having two buttons in the application for adding and subtracting.</p><p>You are also required to show the multiplying result when you press the add button. In real-world examples, any logic might take a considerable amount of time to execute it. For example, fetching a huge number of items and sorting and filtering them. To simulate this scenario, you need to induce some slowness in the application by adding a while loop to the multiply function that will iterate for a long time. Refer to the code below for the same.</p><pre>import { useState } from &quot;react&quot;;<br><br>function App() {<br>  const [add, setAdd] = useState(0);<br>  const [subtract, setSubtract] = useState(0);<br><br>  const multiply = () =&gt; {<br>    let i = 0;<br>    while (i &lt; 2000000000) i++;<br>    console.log(&quot;Multiply&quot;);<br>    return add * 5;<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setAdd(add + 1)}&gt;Add: {add}&lt;/button&gt;<br>      &lt;span&gt;Result: {multiply()}&lt;/span&gt;<br>      &lt;br /&gt;<br>      &lt;button onClick={() =&gt; setSubtract(subtract - 1)}&gt;<br>        Subtract: {subtract}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The graphic below shows the slowness before the result is loaded when you click the add button. Even when the add button produces the multiplying result, clicking the subtract button exhibits the same slowness. This is because the multiply function is re-rendered each time the state changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRTqS8um6l8C4PbPca7BIQ.gif" /><figcaption>Sluggishness and component’s unnecessary re-renderings</figcaption></figure><p>You must prevent unnecessary recalculations of certain values, particularly those that take a lengthy time to compute. In this case, whenever the subtract states are changed, you don’t need to calculate the multiplying result. Hence, the multiply function can be wrapped in a useMemo hook that will only recalculate the value when the dependency array changes. This optimization prevents expensive calculations on every render. The updated code is given below.</p><pre>import { useMemo, useState } from &quot;react&quot;;<br><br>function App() {<br>  const [add, setAdd] = useState(0);<br>  const [subtract, setSubtract] = useState(0);<br><br>  const multiply = useMemo(() =&gt; {<br>    let i = 0;<br>    while (i &lt; 2000000000) i++;<br>    console.log(&quot;Multiply&quot;);<br>    return add * 5;<br>  }, [add]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setAdd(add + 1)}&gt;Add: {add}&lt;/button&gt;<br>      &lt;span&gt;Result: {multiply}&lt;/span&gt;<br>      &lt;br /&gt;<br>      &lt;button onClick={() =&gt; setSubtract(subtract - 1)}&gt;<br>        Subtract: {subtract}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>You can notice in the graphic below that after adding useMemo, the subtract operation removes the sluggishness while the add operation has the expected delay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Wr_LUFNRbKsEk4D1DrrrA.gif" /><figcaption>Sluggishness of subtract operation is prevented using useMemo</figcaption></figure><h3>Summary</h3><p>The performance of an application is always an important aspect of the application. This article has merely discussed a few scenarios in which performance issues could occur and various approaches for optimizing them in React applications. Always optimize your application’s performance to provide a nice user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26be40a21a96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/performance-optimization-in-reactjs-26be40a21a96">Performance Optimization in ReactJs</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Generation using OpenAI API with NodeJs]]></title>
            <link>https://medium.com/globant/image-generation-using-openai-api-with-nodejs-28f8d9a29a44?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28f8d9a29a44</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[dall-e-2]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[openai-api]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 13:36:14 GMT</pubDate>
            <atom:updated>2023-04-10T13:36:14.701Z</atom:updated>
            <content:encoded><![CDATA[<h4>NODEJS SERIES</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETT6Lw3JvyD62KDTMuG3Mg.png" /></figure><p>As part of this article, we will use the OpenAI API to generate an image or piece of art from a natural language description. In response to a text prompt, we create new images using DALL-E models. You may also test this using the OpenAI <a href="https://labs.openai.com/">Labs Interface</a>.</p><h3>OpenAI</h3><p><a href="https://platform.openai.com/docs/introduction">OpenAI</a> is an AI (Artificial Intelligence) research business created in 2015 by Sam Altman and Elon Musk. OpenAI’s mission is to ensure that artificial intelligence benefits all of humanity. Almost any operation that requires reading or producing natural language, code, or graphics can do with the OpenAI API. Competent modern language models that can comprehend and create text are available from OpenAI. Developers use these models in linguistic activities. Content creation to semantic search and classification might use these models. OpenAI makes use of the <a href="https://platform.openai.com/docs/guides/moderation">Moderation API</a>. It helps to display illegal or unsafe information while violating the content policy.</p><h3>OpenAI Models</h3><p>The OpenAI API provides a wide range of models with various features and price ranges. The original base models can also be fine-tuned for your particular use case. Below are some OpenAI models:</p><ul><li><strong>GPT-3 &amp; GPT-4</strong>: <em>comprehend and produce code or plain language.</em></li><li><strong>DALL-E:</strong> <em>generate and alter images in response to a natural language query.</em></li><li><strong>Whisper: </strong><em>convert audio into text.</em></li><li><strong>Moderation:</strong> <em>detect sensitive or unsafe texts.</em></li></ul><p>More details are available in the official <a href="https://platform.openai.com/docs/models">OpenAI Models</a> documentation.</p><h3>Set up an OpenAI Account</h3><p>Create an account on <a href="https://auth0.openai.com/u/login/identifier?state=hKFo2SBRY0FqVHZ1djlGSTZJa3NiYVRNYkFtNGhNR212UkNVNKFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIDNQNmtCd0lfMy1KZjlLYlpiclFUNkN6dzFJLWJORlp1o2NpZNkgRFJpdnNubTJNdTQyVDNLT3BxZHR3QjNOWXZpSFl6d0Q">OpenAI</a> before delving deeper into the code. You could discover a <em>View API keys </em>option under your profile after logging in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VLbTAuz_Rf_fA7pWJeUJg.png" /><figcaption>OpenAI Account Profile</figcaption></figure><p>To use the OpenAI APIs, generate a new secret key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lp4GOMp8OkcqLlKk4h6Y6g.png" /><figcaption>OpenAI API key generation</figcaption></figure><p>Copy the newly generated secret key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ko-Vdf589b5JGrkIPcUo5g.png" /><figcaption>OpenAI API Key</figcaption></figure><h3>NodeJs Server Configuration</h3><p>Now let’s start the NodeJs server with the image generation API. The steps are listed below.</p><ol><li>Create a <em>package.json</em> file by running the command npm init -y .</li><li>Install the dependencies required to set up the server such as express, body-parser, dotenv, and cors.</li></ol><pre>npm i --save express body-parser dotenv cors</pre><p>3. Install openai dependency to use OpenAI APIs.</p><pre>npm i --save openai</pre><p>4. Create a .env file that contains the environment variable OPENAI_API_KEY.</p><pre>OPENAI_API_KEY = &quot;openai API key&quot;</pre><p>5. Start the server with OpenAI configuration.</p><pre>require(&quot;dotenv&quot;).config();<br>const express = require(&quot;express&quot;);<br>const bodyParser = require(&quot;body-parser&quot;);<br>const cors = require(&quot;cors&quot;);<br>const { Configuration, OpenAIApi } = require(&quot;openai&quot;);<br><br>const app = express();<br>const { OPENAI_API_KEY } = process.env;<br><br>const configuration = new Configuration({<br>  apiKey: OPENAI_API_KEY,<br>});<br>const openai = new OpenAIApi(configuration);<br><br>app.use(bodyParser.json());<br>app.use(cors());<br><br>app.listen(8080, () =&gt; {<br>  console.log(&quot;server started&quot;);<br>});</pre><p>6. Add a POST endpoint /create to generate the image.</p><pre>app.post(&quot;/create&quot;, async (req, res) =&gt; {<br>  const { prompt } = req.body;<br>  try {<br>    const response = await openai.createImage({<br>      prompt,<br>      n: 1,<br>      size: &quot;512x512&quot;,<br>    });<br>    res.send(response.data.data[0].url);<br>  } catch (err) {<br>    res.send(err.message);<br>  }<br>});</pre><p>The above POST method takes a prompt in its req.body. Here, a prompt is simply a description of the image to create. We can generate several images between 1 and 10, specified by the parameter n. Image size we can set to either 256x256 or 512x512, or 1024x1024 pixels. Smaller sizes can be generated more quickly. The more specific the description, the more likely you are to receive the desired outcome.</p><h3>User Interface in ReactJs</h3><p>Now, we can set up our User Interface using ReactJs. The steps are listed below.</p><ol><li>Create a React Application using the below command:</li></ol><pre>npx create-react-app app_name</pre><p>2. In the <em>App.js</em> file, render an input text box to enter the user prompts and a button to invoke the API with the given prompt.</p><pre>import { useState } from &quot;react&quot;;<br><br>import &quot;./App.css&quot;;<br><br>function App() {<br>  const [prompt, setPrompt] = useState(&quot;&quot;);<br><br>  const handleChange = (e) =&gt; {<br>    setPrompt(e.target.value);<br>  };<br><br>  return (<br>    &lt;div className=&quot;container-fluid&quot;&gt;<br>      &lt;div className=&quot;form&quot;&gt;<br>        &lt;h1&gt;Create Your Art!&lt;/h1&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          onChange={handleChange}<br>          placeholder=&quot;Enter your image description&quot;<br>        /&gt;<br>        &lt;button type=&quot;submit&quot; className=&quot;btn btn-primary&quot;&gt;<br>          Submit<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>The user interface appears as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtKT9yJK1_tan8GX55JyZA.png" /><figcaption>Image Generation UI</figcaption></figure><p>3. On button submission, use axios to invoke the image-generating API.</p><pre>import { useState } from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br><br>import &quot;./App.css&quot;;<br><br>function App() {<br>  const [prompt, setPrompt] = useState(&quot;&quot;);<br>  const [imageURL, setImage] = useState(&quot;&quot;);<br><br>  const createImg = async () =&gt; {<br>    const response = await axios.post(&quot;http://localhost:8080/create&quot;, {<br>      prompt,<br>    });<br>    setImage(response.data);<br>  };<br><br>  const handleChange = (e) =&gt; {<br>    setPrompt(e.target.value);<br>  };<br><br>  return (<br>    &lt;div className=&quot;container-fluid&quot;&gt;<br>      &lt;div className=&quot;form&quot;&gt;<br>        &lt;h1&gt;Create Your Art!&lt;/h1&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          onChange={handleChange}<br>          placeholder=&quot;Enter your image description&quot;<br>        /&gt;<br>        &lt;button type=&quot;submit&quot; className=&quot;btn btn-primary&quot; onClick={createImg}&gt;<br>          Submit<br>        &lt;/button&gt;<br>        {imageURL &amp;&amp; &lt;img src={imageURL} alt=&quot;prompt&quot; /&gt;}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>Test Snapshots</h3><p>Let’s test our application with some examples to see the magic of AI. Here are some intriguing test snapshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ormmQWmQyt46FxNcI2lxVQ.png" /><figcaption>Pikachu with sunglass</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvXS50VB5X24x5FcOK_7Ag.png" /><figcaption>Tweety wearing cap</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYnEswpEvARdMohjCr75KQ.png" /><figcaption>Patrick star eating popcorn</figcaption></figure><h3>Summary</h3><p>Thus far, we’ve shown how NodeJs and React use the OpenAI API to generate images. The image API also provides the ability to change an existing image in response to new text input and to make changes to an existing image. In this article, we only covered one application of the OpenAI API: image generation. Other options OpenAI offers are text completion, chat completion, speech-to-text conversion, and others. Visit the <a href="https://platform.openai.com/examples">OpenAI</a> page to learn more and to immerse yourself in the magic of AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28f8d9a29a44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/image-generation-using-openai-api-with-nodejs-28f8d9a29a44">Image Generation using OpenAI API with NodeJs</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB/Mongoose Query Optimizations]]></title>
            <link>https://medium.com/globant/mongodb-mongoose-query-optimizations-63cfc6def9d9?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/63cfc6def9d9</guid>
            <category><![CDATA[query-performance]]></category>
            <category><![CDATA[database-query]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 12:55:04 GMT</pubDate>
            <atom:updated>2023-02-07T12:55:04.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>NODEJS SERIES</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdqpcm8EeHlbfjza-qOgew.png" /></figure><p><a href="https://www.mongodb.com/"><strong>MongoDB</strong></a> is a document-oriented NoSQL database. Documents in MongoDB replace the rows of traditional relational data models. Developers can work with changing data models due to MongoDB’s flexibility. MongoDB has grown to become one of the most popular NoSQL databases.</p><p><a href="https://mongoosejs.com/"><strong>Mongoose</strong></a> is an Object Data Modelling (ODM) library used in conjunction with MongoDB. It allows developers to write code in javascript that will then interface with the database, allowing for speedy and simple application development. Like Express provides an abstraction layer over Node, Mongoose does the same for standard MongoDB.</p><p>This article will go through how we may improve the performance of our application by implementing certain query optimizations on MongoDB/Mongoose.</p><h3>Why is Query Optimisation important?</h3><p>The performance of a REST API is heavily dependent on the performance of database queries. If a query takes a long time to process the data, the API response time increases, affecting the application’s performance and user experience.</p><p>Optimizing queries aims to provide fast, effective access to the database. Particularly with complex database query statements, query optimization is crucial. Developers should constantly be aware of how the database processes queries and always think about retrieving the least amount of data possible.</p><p>Let’s start the NodeJs server with a certain Mongoose schema before we begin optimizing. The steps are listed below.</p><ol><li>Create a <em>package.json</em> file by running the command npm init -y</li><li>Install the dependencies required to set up the server, such as express, body-parser, dotenv, mongoose, and autocannon. <a href="https://www.npmjs.com/package/autocannon">Autocannon</a> is optional as it is used only for load testing.</li></ol><pre>npm i --save express body-parser dotenv mongoose<br><br>npm i --save-dev autocannon // autocannon is used for load testing purpose</pre><p>3. Create a .env file that contains environment variables like PORT and DB_CONNECT_URI(MongoDB connection URI)</p><pre>PORT = 8080<br>DB_CONNECT_URI = &quot;MongoDB Connection URI&quot;</pre><p>4. Create a <em>model.js</em> file that should contain your schema definitions.</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const userSchema = new mongoose.Schema(<br>  {<br>    name: String,<br>    email: String,<br>    isActive: Boolean,<br>  },<br>  { collection: &quot;users&quot; }<br>);<br><br>const blogSchema = new mongoose.Schema(<br>  {<br>    title: String,<br>    publication: String,<br>    author: String,<br>  },<br>  { collection: &quot;blogs&quot; }<br>);<br><br>const User = mongoose.model(&quot;users&quot;, userSchema);<br>const Blog = mongoose.model(&quot;blogs&quot;, blogSchema);<br><br>module.exports = { User, Blog };</pre><p>5. Create an <em>index.js </em>file to start the server with connecting database.</p><pre>require(&quot;dotenv&quot;).config();<br>const express = require(&quot;express&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br><br>const { User, Blog } = require(&quot;./model&quot;);<br>const app = express();<br><br>const { PORT, DB_CONNECT_URI } = process.env;<br>const port = PORT || 8080;<br><br>mongoose<br>  .connect(DB_CONNECT_URI)<br>  .then(console.log(&quot;connected&quot;))<br>  .catch(console.log);<br><br>app.listen(port, async () =&gt; {<br>  console.log(`Server started at port ${port}`);<br>});</pre><p>6. The performance of queries with or without optimization can be compared using autocannon. So create an <em>autocannon.js</em> file containing the following snippet that url will carry the endpoint we need to test.</p><pre>&quot;use strict&quot;;<br>const autocannon = require(&quot;autocannon&quot;);<br><br>function test (url){<br>  const instance = autocannon({<br>    url,<br>    connections: 10,<br>    pipelining: 1,<br>    duration: 10,<br>  });<br> <br>  autocannon.track(instance, { renderProgressBar: false });<br>}<br><br>test(url);</pre><p>You can refer to the article below if you are unsure how to use Autocannon.</p><p><a href="https://medium.com/globant/load-testing-nodejs-apis-with-autocannon-c3770478cb36">Load Testing NodeJS APIs with Autocannon</a></p><h3>Query Optimisations</h3><p>Let’s talk about query optimizations that can speed up database access. The optimizations are detailed below.</p><h4>1. Lean Queries</h4><p>Mongoose queries, by default, return instances of the <a href="https://mongoosejs.com/docs/documents.html">Mongoose document class</a>. This document is quite large as it contains <a href="https://mongoosejs.com/docs/tutorials/getters-setters.html">getters/setters</a> and <a href="https://mongoosejs.com/docs/validation.html">validations</a>. Mongoose recommends using the lean operator with all GET requests to improve performance. Adding .lean() at the end of GET queries causes them only to return simple Javascript objects, not Mongoose documents. Simple Javascript objects use less memory. We utilize the lean operator when we don’t need to change the query results. We can avoid using .lean() if we need to modify the query results or use features like save() or getter/setter.</p><p>The query’s syntax should be as follows:</p><pre>await Model.find().lean()</pre><h4>Testing Lean Queries’ Performance</h4><p>Add two GET methods with and without .lean() queries on the <em>index.js</em> file.</p><pre>app.get(&quot;/getAll&quot;, async (req, res) =&gt; {<br>  const users = await User.find({});<br>  res.status(200).send(users);<br>});<br><br>app.get(&quot;/getAllWithLean&quot;, async (req, res) =&gt; {<br>  const users = await User.find({}).lean();<br>  res.status(200).send(users);<br>});</pre><p>Invoke the test() method in <em>autocannon.js</em> file with the above GET endpoints to obtain the performance result.</p><p>The performance result of the query without adding .lean() is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBWfDwiPGVbLjCQJwRbBjQ.png" /><figcaption>Autocannon Performance Result for GET query without .lean()</figcaption></figure><p>The performance result of the query by adding .lean()is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DYgaiRCaUexzaLXM9gcqg.png" /><figcaption>Autocannon Performance Result for GET query with .lean()</figcaption></figure><p>If we compare the test results from the two scenarios, using .lean() queries reduces latency. Additionally, the throughput rate is boosted by lean queries because they can handle more requests per second.</p><h4>2. Projection or using .select()</h4><p>Mongoose GET queries always return every field in the related document, which can be a substantial number of fields. Mongoose projection enables us to pick only the fields we need. A document may frequently include numerous fields, including arrays and embedded documents, which we occasionally may not need. For instance, if the only fields required are username and email, we may return those two and exclude the other fields. Mongoose offers a .select() operator that allows us to specify the fields to return. This modification may even help to improve the performance of our application.</p><h4>Testing Projection’s Performance</h4><p>Add two GET methods with and without .select() in the <em>index.js</em> file.</p><pre>app.get(&quot;/getAll&quot;, async (req, res) =&gt; {<br>  const users = await User.find({});<br>  res.status(200).send(users);<br>});<br><br>app.get(&quot;/getAllWithProjection&quot;, async (req, res) =&gt; {<br>  const users = await User.find({}).select(&#39;name&#39;); // returns only name field<br>  res.status(200).send(users);<br>});</pre><p>Invoke the test() method in <em>autocannon.js</em> file with the above GET endpoints to obtain the performance result.</p><p>The performance result of the GET query without adding .select() is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqvNfRSyhNVxT6eMC9P4yw.png" /><figcaption>Autocannon Performance Result for GET query without .select()</figcaption></figure><p>The performance result of the GET query with .select() is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNMGXgUcAsoxgeIcMxF-Sw.png" /><figcaption>Autocannon Performance Result for GET query with .select()</figcaption></figure><p>Looking at the test results, it is clear that .select() reduces average latency to 5ms. Additionally, they handled 55k requests in 11 seconds, which is faster than queries without .select()</p><h4>3. Parallel DB Operations</h4><p>Many developers use async/await for asynchronous operations. If we have two database operations independent of each other, we don’t need to wait for the initial one to finish. For instance, if there are two databases save operations, it is a typical mistake to code as follows:</p><pre>await Model1.save();<br>await Model2.save();</pre><p>If the above two operations are self-contained, we don’t need to wait for the first to finish. The two operations can be conducted simultaneously, as shown below:</p><pre>await Promise.all([Model1.save(), Model2.save()]);</pre><h4>Testing Parallel DB Operations’ Performance</h4><p>Add two POST methods as below, which shows the above difference.</p><pre>app.post(&quot;/save&quot;, async (req, res) =&gt; {<br>  const user = new User({<br>    name: &quot;Ana Varela&quot;,<br>    email: &quot;ana.varela@gmail.com&quot;,<br>    isActive: true,<br>  });<br>  const blog = new Blog({<br>    title: &quot;Mongoose Query Optimizations&quot;,<br>    author: &quot;Chikku George&quot;,<br>    publication: &quot;Medium&quot;,<br>  });<br>  await user.save();<br>  await blog.save();<br>  res.status(201).send({ message: &quot;Data saved successfully.&quot;, code: 201 });<br>});<br><br>app.post(&quot;/saveParallely&quot;, async (req, res) =&gt; {<br>  const user = new User({<br>    name: &quot;Ana Varela&quot;,<br>    email: &quot;ana.varela@gmail.com&quot;,<br>    isActive: true,<br>  });<br>  const blog = new Blog({<br>    title: &quot;Mongoose Query Optimizations&quot;,<br>    author: &quot;Chikku George&quot;,<br>    publication: &quot;Medium&quot;,<br>  });<br>  await Promise.all([user.save(), blog.save()]);<br>  res.status(201).send({ message: &quot;Data saved successfully.&quot;, code: 201 });<br>});</pre><p>Invoke the <em>test()</em> method in <em>autocannon.js</em> file with the above POST endpoints to obtain the performance result.</p><p>The performance result of the POST query without using parallel DB operations is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzZunVYSKGJKC2Kmybh5Sg.png" /><figcaption>Autocannon Performance Result for POST without using parallel db operations</figcaption></figure><p>The performance result of the POST query using parallel DB operations is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN3WIV7JnJ8SCCpkdUPYhA.png" /><figcaption>Autocannon Performance Result for POST using parallel db operations</figcaption></figure><p>Using the test findings as a comparison, parallel database operations can cut the average latency time to 2.54ms. Additionally, the throughput rate has been raised to 37k requests per 11.01s.</p><h4>4. Indexing</h4><p>Indexes are unique data structures that contain the value of a given field or a set of fields and are ordered by their value. With an index, MongoDB can reduce the number of documents to scan and enhance query performance. In the absence of indices, MongoDB reads each document in a collection to identify those that match the query.</p><p>MongoDB creates an index on the _id parameter by default. On any field, though, we can specify an index if we choose. Additionally, we can define compound indexes on various fields in our schema. For frequent requests, we must establish an index with the necessary fields.</p><p>We can set the index at the field level or schema level.</p><pre>// Setting index on schema level. <br>// Assign either &quot;1&quot;(sort by ascending) or &quot;-1&quot;(sort by descending) to the field.<br>schema.index({field: 1 or -1})</pre><h4>Testing Index Performance</h4><p>Add a GET method to fetch the user data by email as follows:</p><pre>app.get(&quot;/getByEmail/:email&quot;, async (req, res) =&gt; {<br>  const { email } = req.params;<br>  const response = await User.findOne({ email });<br>  res.status(200).send(response);<br>});</pre><p>Invoke the <em>test()</em> method in <em>autocannon.js</em> file with the above GET endpoint to obtain the performance result.</p><p>The performance result of the GET query without indexing is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlGRmGs71LaHqvehgouKhA.png" /><figcaption>Autocannon Performance Result of GET method without Indexing</figcaption></figure><p>Add an index on the email field of User schema as follows and invoke the GET method using autocannon.</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const userSchema = new mongoose.Schema(<br>  {<br>    name: String,<br>    email: {<br>      type: String,<br>      index: 1     //set an index on field level<br>    },<br>    isActive: Boolean,<br>  },<br>  { collection: &quot;users&quot; }<br>);<br><br>userSchema.index({email: 1}); //set an index on schema level<br><br>module.exports = { User, Blog };</pre><p>The performance result of the GET query with indexing is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdrRvA9lP9r0VcSyhGFD2Q.png" /><figcaption>Autocannon Performance Result of GET Method with Indexing</figcaption></figure><p>The test results show that indexing decreased the latency time. Additionally, indexing could handle 67k requests in 11.01 seconds, which is quicker than without indexing.</p><h4>5. Aggregate Pipeline Stages</h4><p>In an aggregate pipeline, the order in which the queries are executed is crucial since it affects how quickly they run.</p><p>Consider the below two schemas in the <em>model.js file. </em>movie_id in the “<em>comments”</em> collection is a reference to the “<em>movies”</em> collection.</p><pre>const commentsSchema = new mongoose.Schema(<br>  {<br>    name: String,<br>    email: String,<br>    movie_id: [{ <br>      type: mongoose.Schema.Types.ObjectId, <br>      ref: &quot;movies&quot; <br>    }],<br>    text: String,<br>    date: Date,<br>  },<br>  { collection: &quot;comments&quot; }<br>);<br>const movieSchema = new mongoose.Schema(<br>  {<br>    plot: String,<br>    cast: [String],<br>    title: String,<br>    released: Date,<br>  },<br>  { collection: &quot;movies&quot; }<br>);<br>const Comments = mongoose.model(&quot;comments&quot;, commentsSchema);<br>const Movies = mongoose.model(&quot;movies&quot;, movieSchema);<br><br>module.exports = { User, Blog, Comments, Movies };</pre><p>Let the query is to fetch all the movies commented on by an user with the email <em>“john_bishop@fakegmail.com”</em>. For this, we need to aggregate two collections, <em>“movies”</em> and <em>“comments”,</em> and keep all the movies commented on by <em>“john_bishop@fakegmail.com”</em>.</p><p>In this situation, the aggregate pipelines can be ordered in one of two ways:<br> 1. In the first instance, we’ll look up the movies table with the movie_id reference. It will unwind all the movies. Later we will filter with the email “<em>john_bishop@fakegmail.com”.</em><br> 2. Only “<em>john_bishop@fakegmail.com” emails will </em>be filtered in the second scenario, reducing the number of records to look up in the “<em>movies”</em> collection. Then we’ll look up the “<em>movies</em>” collection and fetch all the movies’ information.</p><h4>Testing the first type of aggregation</h4><p>Add a GET method to fetch the data as follows. The order of aggregate pipelines will be $lookup followed by $match</p><pre>app.get(&quot;/comments&quot;, async (req, res) =&gt; {<br>  try {<br>    const response = await Comments.aggregate([<br>      {<br>        $lookup: {<br>          from: &quot;movies&quot;,<br>          localField: &quot;movie_id&quot;,<br>          foreignField: &quot;_id&quot;,<br>          as: &quot;movie&quot;,<br>        },<br>      },<br>      {<br>        $unwind: {<br>          path: &quot;$movie&quot;,<br>        },<br>      },<br>      {<br>        $match: {<br>          email: { $eq: &quot;john_bishop@fakegmail.com&quot; },<br>        },<br>      },<br>    ]);<br>    res.status(200).send(response);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>});</pre><p>Invoke the test() method in <em>autocannon.js</em> file with the above GET endpoint to obtain the performance result.</p><p>The performance result of the first aggregate pipeline is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcxFr2a0Jo0UEJ26XkBc8A.png" /><figcaption>Autocannon Performance Result of the first type of aggregation</figcaption></figure><h4>Testing the second type of aggregation</h4><p>Add a GET method to fetch the data as follows. The order of the pipeline is changed in this example. $match will be performed before $lookup.</p><pre>app.get(&quot;/comments-optmization&quot;, async (req, res) =&gt; {<br>  try {<br>    const response = await Comments.aggregate([<br>      {<br>        $match: {<br>          email: { $eq: &quot;john_bishop@fakegmail.com&quot; },<br>        },<br>      },<br>      {<br>        $lookup: {<br>          from: &quot;movies&quot;,<br>          localField: &quot;movie_id&quot;,<br>          foreignField: &quot;_id&quot;,<br>          as: &quot;movie&quot;,<br>        },<br>      },<br>      {<br>        $unwind: {<br>          path: &quot;$movie&quot;,<br>        },<br>      },<br>    ]);<br>    res.status(200).send(response);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>});</pre><p>Invoke the test() method in <em>autocannon.js</em> file with the above GET endpoint to obtain the performance result.</p><p>The performance result of the second aggregate pipeline is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xq4EHXC4AGqDXqzeCJc0hg.png" /><figcaption>Autocannon Performance Result of the first type of aggregation</figcaption></figure><p>Considering the latency time and throughput rate of the examples above, the query performance can be enhanced by changing the order of the phases in the aggregate pipeline.</p><p>The optimized order of aggregation pipeline stages is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*JqpkWJnONLYCqesGVwYxrg.png" /><figcaption>Aggregation Pipeline Stages Optimisation (Credits: <a href="https://severalnines.com/resources/whitepapers/mongodb-aggregation-framework-stages-and-pipelining/">Several9s</a>)</figcaption></figure><h3>Summary</h3><p>When it comes to running database queries, performance is always important. Even in today’s modern big data world, achieving high performance is a major difficulty. The options for mongoose query optimization were merely covered in this article. Utilize them to achieve the desired effects more quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63cfc6def9d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/mongodb-mongoose-query-optimizations-63cfc6def9d9">MongoDB/Mongoose Query Optimizations</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis Cache Implementation with NodeJs]]></title>
            <link>https://medium.com/globant/redis-cache-implementation-with-nodejs-6925f29eb70e?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6925f29eb70e</guid>
            <category><![CDATA[redis-cache-with-nodejs]]></category>
            <category><![CDATA[redis-cache]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 12:13:41 GMT</pubDate>
            <atom:updated>2022-12-01T12:08:01.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>NODEJS SERIES</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StIOFWQx7i6fxDQkiTTBow.png" /></figure><p>In this article, we will look at the Redis cache and explore what makes it fast. In addition, we&#39;ll show how Redis is employed. Furthermore, we&#39;ll observe how to install Redis on a Windows computer and run some fundamental Redis commands. We will also discuss using Redis programmatically with NodeJs using code snippets and test results.</p><h3>What is Redis?</h3><p><a href="https://redis.io/">Redis</a>, which stands for <strong>Remote Dictionary Server</strong>, is an in-memory database. The working memory (RAM) of the computer is where Redis runs. As a result, it works more swiftly. Redis is a schemaless database that stores JSON objects with key-value pairs, much like a NoSQL database. It doesn&#39;t require time to build the schema and initialize the database. Therefore it can perform application testing faster. Rapid tests can boost development productivity.</p><p>Redis, on the other hand, is volatile. Considering that everything inside Redis will be lost if your system suddenly fails. However, we may replicate Redis to create data backups, ensuring that even if the Redis master instance goes down, the replicas will continue to function and contain the data. Redis is frequently used as a cache to enhance the performance of applications. Redis can store the data we access frequently or require a lot of computational time. In the future, we will have quick access to the data if needed.</p><h3>What makes Redis so quick?</h3><p><em>We wonder how Redis can be so speedy being single-threaded.</em></p><p>The fact that Redis is an in-memory database is the primary factor in its speed. Pure memory reading offers fast read/write speeds and quick response times, provided the data you store can&#39;t be larger than the memory.</p><p>The usage of IO multiplexing is the second justification. Redis primarily uses a single thread. However, the operating system permits a single thread to wait on numerous open socket connections simultaneously, thanks to IO multiplexing. It&#39;s possible that a single-threaded design won&#39;t use all the CPU cores in the current hardware. Therefore, it is standard practice for some workloads to operate many Redis instances on a single server to utilize more CPU cores.</p><p>The adoption of efficient low-level data structures is the third argument. Since Redis is an in-memory database, it can use many effective low-level data structures, such as <a href="https://en.wikipedia.org/wiki/Linked_list">LinkedList</a>, <a href="https://en.wikipedia.org/wiki/Skip_list">SkipList</a>, <a href="https://en.wikipedia.org/wiki/Hash_table">HashTable</a>, <a href="https://redis.com/ebook/part-2-core-concepts/01chapter-9-reducing-memory-use/9-1-short-structures/9-1-1-the-ziplist-representation/">ZipList</a>, <a href="http://blog.wjin.org/posts/redis-internal-data-structure-sds.html">SDS</a>, and <a href="http://blog.wjin.org/posts/redis-internal-data-structure-intset.html">IntSet</a>, without having to worry about how to efficiently save them to disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0I9z15x4ramAdiTZj2vvg.png" /><figcaption><strong>Illustration showing IO Multiplexing, Single Threaded Execution &amp; Redis Data Structure</strong> (Credits: Alex Xu)</figcaption></figure><h3>How does Redis cache work?</h3><p>When a client requests data, the server first searches the Redis cache for the appropriate key. If the key is present in the Redis cache, a <strong>cache hit </strong>has occurred, and the user will receive the cached data. If the key is missing from the Redis cache, it is a <strong>cache miss</strong>, and the server will retrieve the most recent information from the database or third-party resources via REST APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdvNQWoaHhc1UY4Y10R93w.png" /><figcaption>Redis caching Illustration</figcaption></figure><h3>Redis Installation on Windows</h3><p>We can install Redis cache on Windows using Windows Subsystem for Linux. Follow the below steps.</p><ol><li>Open the Command prompt in administrator mode</li><li>Run wsl — install command to install Windows Subsystem for Linux (WSL) in Windows.</li><li>Reboot your system to view the changes.</li><li>Set up a new username and password for your Linux system.</li><li>Launch the Linux terminal.</li><li>Install Redis using commands:sudo apt-get update followed by sudo apt-get install redis</li><li>Start the Redis server using theredis-server command.</li><li>Open the Redis CLI by running theredis-cli command</li></ol><p>By default, the Redis server starts at <strong>127.0.0.1:6379</strong> and stores everything as <strong>strings</strong>.</p><h3>Redis Keys Commands</h3><p>Redis offers the following fundamental commands to carry out various operations on keys.</p><ul><li>SET key value , <em>sets the key-value pair.</em></li><li>GET key , <em>get value for a given key.</em></li><li>DEL key, <em>delete a given key.</em></li><li>EXISTS key, <em>check whether a key exists or not.</em></li><li>KEYS pattern, f<em>ind all the keys that match a specific pattern.</em></li><li>flushall, <em>delete everything inside Redis.</em></li><li>SETEX key seconds value, <em>set key-value that expires after the given seconds.</em></li><li>ttl key,<em> returns the expiry time left for a key.</em></li></ul><p>The usage and output of the commands are demonstrated in the below code snippet.</p><pre>chikku@DESKTOP-21GGVDA:~$ redis-cli<br>127.0.0.1:6379&gt; set firstName Luke<br>OK<br>127.0.0.1:6379&gt; set lastName Antony<br>OK<br>127.0.0.1:6379&gt; set age 32<br>OK<br>127.0.0.1:6379&gt; set email luke@gmail.com<br>OK<br>127.0.0.1:6379&gt; get email<br>&quot;luke@gmail.com&quot;<br>127.0.0.1:6379&gt; keys *<br>&quot;age&quot;<br>&quot;lastName&quot;<br>&quot;email&quot;<br>&quot;firstName&quot;<br>127.0.0.1:6379&gt; exists email<br>(integer)1<br>127.0.0.1:6379&gt; del email<br>(integer)1<br>127.0.0.1:6379&gt; exists email<br>(integer)0<br>127.0.0.1:6379&gt; keys *<br>&quot;age&quot;<br>&quot;lastName&quot;<br>&quot;firstName&quot;<br>127.0.0.1:6379&gt; setex city 10 Bangalore<br>OK<br>127.0.0.1:6379&gt; keys *<br>&quot;age&quot;<br>&quot;lastName&quot;<br>&quot;firstName&quot;<br>&quot;city&quot;<br>127.0.0.1:6379&gt; ttl city<br>(integer)4<br>127.0.0.1:6379&gt; ttl city<br>(integer)3<br>127.0.0.1:6379&gt; ttl city<br>(integer)2<br>127.0.0.1:6379&gt; ttl city<br>(integer)1<br>127.0.0.1:6379&gt; ttl city<br>(integer)-2<br>127.0.0.1:6379&gt; keys *<br>&quot;age&quot;<br>&quot;lastName&quot;<br>&quot;firstName&quot;<br>127.0.0.1:6379&gt; flushall<br>OK<br>127.0.0.1:6379&gt; keys *<br>(empty list or set)</pre><h3>Redis List Commands</h3><p>Redis Lists are simple string lists. We can append elements to the list&#39;s head or tail in Redis lists. The commands are given below.</p><ul><li>lpush key value ,<em> push the element to the leftmost end of the array.</em></li><li>rpush key value , <em>push the element to the rightmost end of the array.</em></li><li>lrange key startIndex stopIndex, <em>display the list of elements between the start and stop indexes</em></li><li>lpop key , <em>pop the leftmost element of the array.</em></li><li>rpop key, <em>pop the rightmost element of the array.</em></li></ul><p>The code snippet below shows the use and output of the Redis list commands.</p><pre>chikku@DESKTOP-21GGVDA:~$ redis-cli<br>127.0.0.1:6379&gt; lpush colors red<br>(integer)1<br>127.0.0.1:6379&gt; lrange colors 0 1<br>&quot;red&quot;<br>127.0.0.1:6379&gt; lpush colors blue<br>(integer)2<br>127.0.0.1:6379&gt; lrange colors 0 2<br>&quot;blue&quot;<br>&quot;red&quot;<br>127.0.0.1:6379&gt; rpush colors green<br>(integer)3<br>127.0.0.1:6379&gt; lrange colors 0 3<br>&quot;blue&quot;<br>&quot;red&quot;<br>&quot;green&quot;<br>127.0.0.1:6379&gt; lpop colors<br>&quot;blue&quot;<br>127.0.0.1:6379&gt; lrange colors 0 2<br>&quot;red&quot;<br>&quot;green&quot;<br>127.0.0.1:6379&gt; rpop colors<br>&quot;green&quot;<br>127.0.0.1:6379&gt; lrange colors 0 2<br>&quot;red&quot;<br>127.0.0.1:6379&gt;</pre><h3>Redis Set Commands</h3><p>Every element inside a Set is unique, unlike in an array. Elements in an array can be retrieved using an index, which is not allowed in a Set because it requires keys. In contrast to an array, which maintains its insertion order, a set is not ordered. The sequence in which the items in a Set appear cannot be predicted. The Set commands are as follows.</p><ul><li>sadd key member, <em>add members to a set.</em></li><li>smembers key, <em>display the members of a given set.</em></li><li>srem key member, <em>remove a given member from a set.</em></li></ul><p>The usage and outcomes of Redis Set commands are shown below.</p><pre>chikku@DESKTOP-21GGVDA:~$ redis-cli<br>127.0.0.1:6379&gt; sadd fruits Apple Orange Grapes Mango<br>(integer)4<br>127.0.0.1:6379&gt; smembers fruits<br>&quot;Mango&quot;<br>&quot;Grapes&quot;<br>&quot;Orange&quot;<br>&quot;Apple&quot;<br>127.0.0.1:6379&gt; srem fruits Grapes<br>(integer)1<br>127.0.0.1:6379&gt; smembers fruits<br>&quot;Mango&quot;<br>&quot;Orange&quot;<br>&quot;Apple&quot;<br>127.0.0.1:6379&gt;</pre><h3>Redis Hash Commands</h3><p>Hashing allows you to store key-value pairs inside of a single key. The Hash commands are listed below.</p><ul><li>hset key field value, <em>set a key-value pair to a hash.</em></li><li>hget key field, <em>get the value of a hash field.</em></li><li>hgetall key, <em>get all the key-value pairs of a hash.</em></li><li>hdel key field , <em>delete a given field from a hash.</em></li><li>hexists key field , c<em>heck whether the field exists in hash or not.</em></li></ul><p>The following lists the usage and outcomes of Redis Hash commands.</p><pre>chikku@DESKTOP-21GGVDA:~$ redis-cli<br>127.0.0.1:6379&gt; hset address city Bangalore<br>(integer)1<br>127.0.0.1:6379&gt; hset address state Karnataka<br>(integer)1<br>127.0.0.1:6379&gt; hset address country India<br>(integer)1<br>127.0.0.1:6379&gt; hget address city<br>&quot;Bangalore&quot;<br>127.0.0.1:6379&gt;hgetall address<br>&quot;city&quot;<br>&quot;Bangalore&quot;<br>&quot;state&quot;<br>&quot;Karnataka&quot;<br>&quot;country&quot;<br>&quot;India&quot;<br>127.0.0.1:6379&gt;hexists address city<br>(integer)1<br>127.0.0.1:6379&gt;hdel address city<br>(integer)1<br>127.0.0.1:6379&gt;hexists address city<br>(integer)0<br>127.0.0.1:6379&gt;hgetall address<br>&quot;state&quot;<br>&quot;Karnataka&quot;<br>&quot;country&quot;<br>&quot;India&quot;<br>127.0.0.1:6379&gt;</pre><h3>Redis caching with Nodejs</h3><p>We are creating an Express application with GET and POST endpoints. We use external, fake REST APIs (<em>jsonplaceholder.typicode.com/posts</em>) to fetch a list of posts and to create new posts.</p><p>Follow the below steps to set up the application.</p><ol><li>Create package.json with the npm init -y command.</li><li>Install all the required dependencies for the Express app as follows:</li></ol><pre>npm i express dotenv axios body-parser</pre><p>2. Install Redis dependency by using npm i ioredis</p><p>3. Your package.json file should contain the following.</p><pre>{<br>  &quot;name&quot;: &quot;redis-setup&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;axios&quot;: &quot;^1.1.3&quot;,<br>    &quot;body-parser&quot;: &quot;^1.20.1&quot;,<br>    &quot;dotenv&quot;: &quot;^16.0.3&quot;,<br>    &quot;express&quot;: &quot;^4.18.2&quot;,<br>    &quot;ioredis&quot;: &quot;^5.2.3&quot;<br>  }<br>}</pre><p>4. Add the Redis host, port, ttl (Time-to-Live) and timeout to the <em>.env</em> file. The <em>.env</em> file also includes an optional REST API URL that serves the Redis demonstration&#39;s purpose.</p><p>The code snippet below lists the contents of the <em>.env</em> file.</p><pre>REDIS_HOST = 127.0.0.1<br>REDIS_PORT = 6379<br>REDIS_TTL = 30<br>REDIS_TIMEOUT = 5000<br>BASE_URL = https://jsonplaceholder.typicode.com/posts</pre><p>5. Start your server inside the <em>index.js</em> file as given below.</p><pre>require(&#39;dotenv&#39;).config();<br>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const app = express();<br><br>app.use(bodyParser.json());<br><br>app.listen(8000, () =&gt; {<br>    console.log(&#39;server started!&#39;);<br>});</pre><p>6. Create a <em>caching.js</em> file that contains the following:</p><ul><li>A Redis instance with host, port and commandTimeout. If a command doesn&#39;t return a reply within the specified milliseconds, a &quot;command timed out&quot; error will be thrown.</li><li>set() method to set the cache key-value pair with an expiry. Before setting, the data should be stringified, as Redis values are always strings.</li><li>get() method to retrieve key-value pairs.</li><li>del() method to remove the cache key.</li></ul><p>The code snippet for <em>caching.js</em> is added below for your reference.</p><pre>const Redis = require(&quot;ioredis&quot;);<br>const { REDIS_HOST, REDIS_PORT, REDIS_TTL, REDIS_TIMEOUT } = process.env;<br><br>let redis;<br><br>// Create a Redis instance<br>(async () =&gt; {<br>    redis = new Redis({<br>        host: REDIS_HOST,<br>        port: REDIS_PORT,<br>        commandTimeout: REDIS_TIMEOUT<br>    });<br>    redis.on(&quot;error&quot;, (err) =&gt; {<br>        console.log(err);<br>    });<br>})();<br><br>// Get key data from Redis cache<br>async function getCache(key) {<br>    try {<br>        const cacheData = await redis.get(key);<br>        return cacheData;<br>    } catch (err) {<br>        return null;<br>    }<br>}<br><br>// Set Redis cache Key with a given expiry<br>function setCache(key, data, ttl = REDIS_TTL) {<br>    try {<br>        redis.set(key, JSON.stringify(data), &quot;EX&quot;, ttl);<br>    } catch (err) {<br>        return null;<br>    }<br>}<br><br>// Remove given Redis cache key<br>function removeCache(key) {<br>    try {<br>        redis.del(key);<br>    } catch (err) {<br>        return null;<br>    }<br>}<br><br>module.exports = { getCache, setCache, removeCache };</pre><h4>GET Method with Caching</h4><p>We are creating a GET endpoint /getAll to fetch all the posts from an external API. We need to choose a unique cache key to store the values. Furthermore, by invoking the getCache(key) method, we will determine if the cache key has already been assigned a value. The user will receive the cached data if the key is found in the cache, known as a <strong>cache hit</strong>. If the key is not found in the cache, it is considered a <strong>cache miss</strong>, and the data will be fetched from the REST API, and the setCache(key, data) method will be called to set the value. Refer to the below code snippet to create the GET endpoint.</p><pre>require(&#39;dotenv&#39;).config();<br>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const axios = require(&#39;axios&#39;);<br>const { getCache, setCache } = require(&#39;./caching&#39;);<br>const app = express();<br><br>const { BASE_URL } = process.env;<br>const cacheKey = `getAll/posts`;<br><br>//Middleware<br>app.use(bodyParser.json());<br><br>//GET Posts<br>app.get(&#39;/getAll&#39;, async (req, res, next) =&gt; {<br>    try{<br>        const response = {};<br>        const cacheData = await getCache(cacheKey);<br>        if(cacheData) {<br>            response[&#39;message&#39;] = &#39;cache hit&#39;;<br>            response[&#39;posts&#39;] = JSON.parse(cacheData);<br>        }else {<br>            const result = await axios.get(BASE_URL);<br>            const { data } = result;<br>            response[&#39;message&#39;] = &#39;cache miss&#39;;<br>            response[&#39;posts&#39;] = data;<br>            setCache(cacheKey, data);<br>        }<br>        res.status(200).send(response);<br>    }catch(err) {<br>        res.status(400).send(err);<br>    }<br>})<br><br>app.listen(8000, () =&gt; {<br>    console.log(&#39;server started!&#39;);<br>});</pre><h4>Result of GET method before caching</h4><p>To test our GET endpoint, we are using the Postman tool. Send the GET request to fetch the result. The below image shows the result of GET posts before caching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Dk4YF8_GXtJEBTHEZx2CUQ.png" /><figcaption>GET Method Test Result before caching</figcaption></figure><p>A new key will be added to the Redis cache. We can identify the newly added key on Redis by inspecting the keys as follows.</p><pre>127.0.0.1:6379&gt; keys *<br>1)&quot;getAll/posts&quot;<br>127.0.0.1:6379</pre><h4>Result of GET method after caching</h4><p>Send the GET request again to fetch the result once the cache key is set in Redis. The data will be fetched from the Redis cache. The below image shows the Postman result of GET posts after caching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*w4Ypq3g-cLl7GS2Hvfw4yw.png" /><figcaption>GET Method Test Result after caching</figcaption></figure><p>You can detect the performance difference by carefully observing the Postman test results. After using Redis caching, the response time is significantly slashed.</p><h4>POST Method with Caching</h4><p>We are creating a POST endpoint /create to add a new post to the external API. The data is passed inside the req.body. The Redis key already set for the post result should be erased when a new post is added. The removeCache() method will do that. By doing this, data inconsistency can be prevented. Refer to the below code snippet to create the POST endpoint.</p><pre>require(&#39;dotenv&#39;).config();<br>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const axios = require(&#39;axios&#39;);<br>const { removeCache } = require(&#39;./caching&#39;);<br>const app = express();<br><br>const { BASE_URL } = process.env;<br>const cacheKey = `getAll/posts`;<br><br>//Middleware<br>app.use(bodyParser.json());<br><br>//Create new post<br>app.post(&#39;/create&#39;, async(req, res, next) =&gt; {<br>    try{<br>        const response = await axios.post(BASE_URL, req.body);<br>        if(response) {<br>            const { data: posts } = response;<br>            removeCache(cacheKey);<br>            res.status(201).send(posts);<br>        }<br>    }catch(err) {<br>        res.status(400).send(err);<br>    }<br>});<br><br>app.listen(8000, () =&gt; {<br>    console.log(&#39;server started!&#39;);<br>});</pre><h4>Result of the POST method</h4><p>Send the POST request in the Postman tool. The body of the POST request is sent as JSON. The below image shows the result of creating post API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*B_gy-1vWZGh8L6wpBMbgZg.png" /><figcaption>POST Method Test Result in Postman</figcaption></figure><p>The Redis key is deleted upon the creation of a new post.</p><h3>Summary</h3><p>Redis cache utilization with NodeJs has been the topic of our discussion up to this point. Using Redis as a cache improves data retrieval performance by minimizing the need to access the slower underlying storage layer. Redis works in a single thread, yet it is still a fast in-memory database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6925f29eb70e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/redis-cache-implementation-with-nodejs-6925f29eb70e">Redis Cache Implementation with NodeJs</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing NodeJS APIs with Autocannon]]></title>
            <link>https://medium.com/globant/load-testing-nodejs-apis-with-autocannon-c3770478cb36?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3770478cb36</guid>
            <category><![CDATA[api-testing-tools]]></category>
            <category><![CDATA[load-testing-tools]]></category>
            <category><![CDATA[autocannon]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[nodejs-api]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Tue, 11 Oct 2022 12:28:43 GMT</pubDate>
            <atom:updated>2022-10-11T12:28:43.857Z</atom:updated>
            <content:encoded><![CDATA[<h4>NODEJS SERIES</h4><h4>A guide to how we can load test NodeJS APIs using Autocannon</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_MB2L-eXkwTnYqeZrf1LQ.png" /></figure><p>As a developer, we always have a concern regarding the API’s response time such that it can’t be a bottleneck for the consumers. So we need to ensure that the response time will not affect the application’s performance even if multiple users are using it concurrently.</p><p>Tests are always an integral part of an application to ensure its smooth functioning. <em>How can we test our APIs that will support concurrent user requests? — </em><strong>Autocannon, a load testing package, can simulate high traffic in our application.</strong></p><h4>Autocannon</h4><p><a href="https://www.npmjs.com/package/autocannon">Autocannon</a> is an HTTP/1.1 benchmarking tool written in NodeJS, widely used to measure the performance of an application. With autocannon, we can simulate multiple requests per second to load-test our application.</p><h4>Installation</h4><p>Install autocannon globally in your project.</p><pre>npm install -g autocannon</pre><h4>Testing Command</h4><pre>autocannon [opts] URL</pre><h4><strong>Available Options</strong></h4><p>More options you can find <a href="https://www.npmjs.com/package/autocannon">here.</a></p><pre><strong>-c | --connections</strong><br>Number of concurrent connections to use<br>By default, its value is 10</pre><pre><strong>-p | --pipeline</strong><br>Number of pipelined requests to use<br>By default, its value is 1</pre><pre><strong>-d | --duration<br></strong>Number of seconds to run the autocannon<br>By default, its value is 10</pre><pre><strong>-w | --workers</strong><br>Number of worker threads to fire requests</pre><pre><strong>-m | --method<br></strong>HTTP method to use<br>By default, its value is &#39;GET&#39;</pre><pre><strong>-t | --timeout</strong><br>Number of seconds before timing out and resetting a connection<br>By default, its value is 10</pre><pre><strong>-j | --json</strong><br>Print the output as newline delimited JSON<br>By default, its value is false</pre><pre><strong>-f | --forever</strong><br>Run the benchmark forever</pre><p>When you run the command, if you come across any error like <strong>running scripts disabled on the system</strong>, set the execution policy as follows:</p><pre>Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted</pre><p><em>Let’s play with some code examples.</em></p><p>I set up a sample project where my database contains only one collection called hobbies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*3n-_sqAbjkZxPqUtbS492g.png" /><figcaption>Hobbies Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6YFSlt3r6uHXLRHu9ASYKg.png" /><figcaption>Get all Hobbies &amp; Save new Hobbies</figcaption></figure><h4>Autocannon command for my GET Request</h4><pre>autocannon -c 500 -d 5 <a href="http://localhost:8000/getAll">http://localhost:8000/getAll</a> // Running 500 connections in 5 seconds</pre><h4>Test Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*PLO9Izop6S93paijbmuOGw.png" /><figcaption>Credit: Author</figcaption></figure><h4>Autocannon command for my POST Request</h4><pre>autocannon -m POST -H “Content-Type:application/x-www-form-urlencoded” -b “name=swimming&amp;active=true” <a href="http://localhost:8000/save">http://localhost:8000/save</a>  // specify Header(-H) and Body (-b)</pre><h4>Test Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Ob-6UhSDGbaOTFwScHjU1A.png" /><figcaption>Credit: Author</figcaption></figure><p>Autocannon outputs two tables of data:</p><ol><li><strong>Request Latency — </strong><em>It shows the request time at 2.5%(fast), 50%(median), 97.5%(slow), and 99%(slowest) along with an average time.</em></li><li><strong>Request Volume — </strong><em>It shows the number of requests sent and number of bytes downloaded per second.</em></li></ol><p><em>Instead of running test commands from the command line, we can also run them programmatically.</em></p><pre>autocannon(opts[, cb])</pre><p><strong><em>opts</em></strong> is the configuration options for the autocannon instance and <strong><em>cb</em></strong>, the callback which is called on completion of the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaJQB5Jl9XWuR3GZSePN9Q.png" /><figcaption>Autocannon GET &amp; POST requests programmatically</figcaption></figure><h4>Test Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jutEdLFF9F9uv-HchqlPVw.png" /><figcaption>Credit: Author</figcaption></figure><p>If you closely watch the above test result, many things got displayed as below:</p><pre><strong>start</strong><br>Date object when test started</pre><pre><strong>finish</strong><br>Date object when test ended</pre><pre><strong>errors</strong><br>Number of connection errors</pre><pre><strong>timeouts</strong><br>Number of connection timeouts</pre><pre><strong>mismatches</strong><br>Number of requests with a mismatched body</pre><pre><strong>non2xx</strong><br>Number of non-2xx response status codes received</pre><pre><strong>requests</strong><br>Number of requests per second</pre><pre><strong>latency</strong><br>Request time</pre><pre><strong>throughput<br></strong>Response data throughput per second</pre><p><strong><em>request</em></strong>, <strong><em>latency</em></strong> and <strong><em>throughput</em></strong> are percentile-objects with the following values:</p><pre><strong>min</strong><br>The lowest value.</pre><pre><strong>max</strong><br>The highest value.</pre><pre><strong>average</strong><br>The average (mean) value.</pre><pre><strong>stddev</strong><br>The standard deviation.</pre><pre><strong>p*</strong><br>The percentile value. The percentile properties are: p2_5, p50, p75, p90, p97_5, p99, p99_9, p99_99, p99_999.</pre><h4>Autocannon Events</h4><p>An autocannon instance is an Event Emitter. So it emits several events. Some are given below. More can find <a href="https://www.npmjs.com/package/autocannon">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcdj1g2EXbQdAHpzlvMp3w.png" /><figcaption>Credit: Author</figcaption></figure><pre><strong>start<br></strong>Emitted when autocannon instance is setup and started<strong>.</strong></pre><pre><strong>done<br></strong>Emitted when the autocannon finishes a benchmark.</pre><pre><strong>track<br></strong>Track the progress of autocannon. <br>Configuration options for tracking are:</pre><pre><strong>   1. outputStream<br>   </strong>The stream to output to.</pre><pre><strong>   2. renderProgressBar<br>   </strong>A boolean value indicating whether to display progress bar or    not. By default, it’s value is true.</pre><pre><strong>   3. renderResultsTable<br>   </strong>A boolean value indicating whether to display result table or not. By default, it’s value is true.</pre><pre><strong>   4. renderLatencyTable<br>  </strong> A boolean value indicating whether to display latency table. By default, it’s value is false.</pre><pre><strong>   5. progressBarString<br>  </strong> A string defining the format of the progress display output.</pre><p><strong>Have fun load testing your APIs with Autocannon. Thank You:)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3770478cb36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/load-testing-nodejs-apis-with-autocannon-c3770478cb36">Load Testing NodeJS APIs with Autocannon</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twilio OTP Authentication]]></title>
            <link>https://medium.com/globant/twilio-otp-authentication-12002a139e38?source=rss-64a627979b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/12002a139e38</guid>
            <category><![CDATA[twilio]]></category>
            <category><![CDATA[sms-service]]></category>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[twilio-with-nodejs]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Chikku George]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 13:39:06 GMT</pubDate>
            <atom:updated>2022-08-25T13:39:06.139Z</atom:updated>
            <content:encoded><![CDATA[<h4>NodeJS Series</h4><h4>A guide to Twilio OTP Authentication with NodeJS</h4><p><strong><em>As part of this article, we will walk through how we can send a verification code via SMS to a user and verify the same code using Twilio services.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NBHgmdhNvg2IGpk7gXn6Q.png" /></figure><p><strong>Twilio</strong> is a cloud communication platform. With the Twilio services, we can send a text via SMS, Whatsapp, and Email, place a voice message, connect a call and start a chat from our application. All these can be done with just a few lines of code.</p><p>We can just pay for what service we are using. Twilio also provides a free trial account which developers can easily use for development and testing purposes.</p><h3>Twilio OTP Authentication Work flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*g77Jf2wr5Ji0jBNahpmBrQ.png" /><figcaption>Credit: Author</figcaption></figure><p>Our application sends an API request to enable Twilio to send a verification code to the user via SMS. Once the user has entered the code on our application, it again sends an API request to enable Twilio to verify whether the code entered is correct or not.</p><h3>Twilio Account &amp; Verify Service Setup</h3><h4>Step 1: Create an account on <a href="https://www.twilio.com/try-twilio">Twilio</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_zC7sGddDwrAykst9Toyw.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 2: Choose “<strong>SMS”</strong> as the Twilio product and “<strong>Identity and Verification”</strong> as the plan</h4><p>Also give other details as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIao17HnLNDFupslKNPCSg.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 3: Choose an Account</h4><p>By default, you will be having an account called “<strong>My first Twilio account</strong>”. You can also create new accounts if you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVaJIipvX6JhQf6LIWzuag.png" /><figcaption>Credit: Author</figcaption></figure><p>Each account can be identified with an <strong>“Account SID”</strong> and <strong>“Auth Token”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*c3GaDS7byw89lgHwKP1yuQ.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 4: Add “Verify” product to the “Develop” section</h4><p>By default, <strong>“Verify”</strong> product can be found under <strong>“Develop”</strong> section. If not, add the product from <strong>“Explore Products”</strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6sJt7pfgUXF_Ue2XrYDM7w.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 5: Create a verify service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga0yUQjKMMpY710ZD1NwLw.png" /><figcaption>Credit: Author</figcaption></figure><p>Provide a custom service name and choose <strong>“SMS”</strong> as the verification channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqzYoAgwyQAJTkadnZgomw.png" /><figcaption>Credit: Author</figcaption></figure><p>Each service will have a <strong>“Service SID”</strong>. We can also set the length of the verification code. Twilio recommends a code length of at least <strong>6 digits</strong> for better security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv2ULmeGn7IL2Qs8NIVD3Q.png" /><figcaption>Credit: Author</figcaption></figure><h3>Node APIs for Send &amp; Verify code</h3><h4>Step 1: Create a package.json file</h4><pre>npm init -y</pre><h4>Step 2 : Install “twilio” dependency</h4><pre>npm install twilio</pre><h4>Step3: Install required dependencies for a NodeJs App</h4><pre>npm install express body-parser dotenv</pre><p>Your package.json looks like below which you can change accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*o-TmqHQGLx5RgAuAN-NfUw.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 4: Create a .env file and copy Twilio credentials</h4><pre>PORT = &quot;Your Port&quot;<br>TWILIO_ACCOUNT_SID = &quot;Your Twilio Account SID&quot;<br>TWILIO_AUTH_TOKEN = &quot;Your Twilio AUTH Token&quot;<br>TWILIO_SERVICE_SID = &quot;Your Twilio Service SID&quot;</pre><h4>Step 5: Create an entry file “<em>index.js</em>”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*761whDqXWkzMqbjxSUpYRw.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 6: Create a router file inside “src/routes/” to route the Twilio OTP operations</h4><p>We have two routes:</p><ol><li>Send OTP -&gt; To send a verification code to the user’s phone number</li><li>Verify OTP -&gt; To verify the code which has been send to the user</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTxXljjQZQgPkJ3rgSx9Hg.png" /><figcaption>Credit: Author</figcaption></figure><h4>Step 7: Create a controller file inside “src/controller” to handle the OTP operations</h4><p>Import Twilio with the credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scIPM8SV8MxwU-YH5hQMDQ.png" /><figcaption>Credit: Author</figcaption></figure><p><strong>sendOTP() </strong>method accepts two parameters: <strong>countryCode</strong> and <strong>phoneNumber</strong> and will send an OTP to the given phone number using <strong>verifications</strong> services of Twilio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI0GUSyLOy5yRygNhOax5A.png" /><figcaption>Credit: Author</figcaption></figure><p><strong>verifyOTP()</strong> accepts <strong>countryCode</strong>, <strong>phoneNumber</strong> and <strong>OTP</strong> and it verifies the OTP using <strong>verificationChecks</strong> services of Twilio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQNWFbJ_8AfCZ5WbQkT3MA.png" /><figcaption>Credit: Author</figcaption></figure><h3>API Test Results using Postman</h3><h4><strong>1. Send OTP API</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SBaN_OjTSHGaNpJsQXSfQ.png" /><figcaption>Credit: Author</figcaption></figure><p>You will get the OTP in your phone number as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28cDZ_a1sMD0dk2D4XjiPQ.jpeg" /><figcaption>Credit: Author</figcaption></figure><h4>2. <strong>Verify OTP API</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIyQmo7ffc91KeJ5f4QncA.png" /><figcaption>Credit: Author</figcaption></figure><p>With the Twilio services, we don’t need to write from scratch to authenticate a user’s phone number. Twilio ensures the SMS reaches the intended user.</p><h3>References</h3><ol><li><a href="https://www.twilio.com/">https://www.twilio.com/</a></li><li><a href="https://github.com/twilio">https://github.com/twilio</a></li><li><a href="https://www.youtube.com/watch?v=ekv6Xh_Im5c">https://www.youtube.com/watch?v=ekv6Xh_Im5c</a></li></ol><h4>Happy Coding with Twilio:)</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12002a139e38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/twilio-otp-authentication-12002a139e38">Twilio OTP Authentication</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>