<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Dhinesh Kumar</title>
    <description>The latest articles on Forem by Dhinesh Kumar (@dhinesh03).</description>
    <link>https://forem.com/dhinesh03</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F684829%2F7159e269-35ff-4c13-814b-b6f314c95b47.png</url>
      <title>Forem: Dhinesh Kumar</title>
      <link>https://forem.com/dhinesh03</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/dhinesh03"/>
    <language>en</language>
    <item>
      <title>Organizing Express Routes with a Route Loader</title>
      <dc:creator>Dhinesh Kumar</dc:creator>
      <pubDate>Fri, 24 Feb 2023 08:31:16 +0000</pubDate>
      <link>https://forem.com/dhinesh03/organizing-express-routes-with-a-route-loader-l73</link>
      <guid>https://forem.com/dhinesh03/organizing-express-routes-with-a-route-loader-l73</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Express Js is one of the most widely used Node frameworks for developing web applications. Its robust features and minimalistic capabilities have made it popular with developers for its easy-to-use nature. However, as an application grows in complexity, organizing the code can become a challenge. Express doesn't impose any folder or architectural structure, which can lead to a cluttered and hard-to-manage codebase.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem
&lt;/h2&gt;

&lt;p&gt;As your application grows, the complexity of your API will grow in tandem. To organize your code, you may want to split up your routes into multiple files. You can structure your code based on technical responsibilities (e.g. controllers, models, services, utils, tests) or domain modules (e.g. users, orders, products). However, manually importing all your routes one by one into the app.js file is not ideal.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Solution (using ESM)
&lt;/h2&gt;

&lt;p&gt;The problem of splitting the routes into multiple files can be solved by using a Route Loader. A Route Loader is a function that takes a glob pattern and automatically imports all your route files. You only need to call the function once in your app.js file, and it will take care of the rest.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import { Router } from 'express';
import glob from 'fast-glob';
import fs from 'fs';
import path from 'path';

const BASE_DIR = path.join(__dirname, '..');

export default async function RouteLoader(globPattern) {
  let router = Router();
  let files = [];
  try {
    files = await glob(globPattern, { cwd: BASE_DIR });
  } catch (error) {
    console.error(error);
  }

  for (const file of files) {
    if (fs.statSync(file).isFile() &amp;amp;&amp;amp; path.extname(file).toLowerCase() === '.js') {
      try {
        const routeModule = await import(path.resolve(file));
        router = (routeModule.default || routeModule)(router);
      } catch (e) {
        throw new Error(`Error when loading route file: ${file} [ ${e.toString()} ]`);
      }
    }
  }

  return router;
}

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

&lt;/div&gt;



&lt;p&gt;With this Route Loader, you can split up your routes into multiple files and organize them in a way that makes sense for your application. You only need to call the RouteLoader function once in your app.js file.&lt;br&gt;
Here's an example of using the RouteLoader function in your main Express application file (usually named app.js or index.js). Let's assume you have your routes organized in a directory called "routes", with each file representing a different endpoint or resource. You can use the RouteLoader function to load all these routes into your application with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
import RouteLoader from './RouteLoader';

const app = express();

const routes = await RouteLoader('routes/**/*.js');
app.use('/', routes);

app.listen(3000, () =&amp;gt; {
    console.log('Example app listening on port 3000!');
});

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

&lt;/div&gt;



&lt;p&gt;Your router should be defined like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function (router) {
    // create a new user
    router.post('/api/users/create', passport.authenticate('jwt', { session: false }), async function (req, res) { 
        /** your route implementation here*/
    });
    return router; 
}

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

&lt;/div&gt;



&lt;p&gt;In this example, RouteLoader will look for all files with a .js extension in the "routes" directory and its subdirectories and load them as routes into the Express application. The use method on the app object is used to mount the routes on a specific path, in this case, the root / path.&lt;br&gt;
You can also organize your routes by domain modules, for example, you can have separate files for handling users, orders, and products in separate files within the "routes" directory:&lt;/p&gt;

&lt;p&gt;routes/&lt;br&gt;
  |- users.js&lt;br&gt;
  |- orders.js&lt;br&gt;
  |- products.js&lt;/p&gt;

&lt;p&gt;In this case, you can modify the RouteLoader function to look for routes in the routes directory only, rather than its subdirectories:&lt;br&gt;
&lt;code&gt;const routes = await RouteLoader('routes/*.js');&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Organizing your routes is an important step in keeping your Express application maintainable and scalable. By using a Route Loader, you can split your routes into multiple files, making it easier to manage your codebase and quickly add new routes as your application grows.&lt;/p&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>router</category>
    </item>
    <item>
      <title>React Hooks vs Svelte - Why I chose Svelte?</title>
      <dc:creator>Dhinesh Kumar</dc:creator>
      <pubDate>Thu, 12 Aug 2021 12:59:29 +0000</pubDate>
      <link>https://forem.com/dhinesh03/react-hooks-vs-svelte-why-i-chose-svelte-3nkg</link>
      <guid>https://forem.com/dhinesh03/react-hooks-vs-svelte-why-i-chose-svelte-3nkg</guid>
      <description>&lt;p&gt;I work at ZoomRx and I have been developing web applications for the past 10 years. ZoomRx is a strategic healthcare consulting firm. All of my front-end colleagues are strong in Javascript fundamentals, so we have the leverage to adopt and experiment with new frameworks frequently. I experienced a lot of javascript libraries/frameworks, especially Jquery, Ember, Mithril, Angular, React and React with Hooks. I love a few aspects in each of these frameworks but I'm not fulfilled and never stopped looking for alternatives. I was just looking for a framework which is developer friendly and highly performant. I even had ideas for building my own framework. Then In the middle of 2019 I came across Svelte and was impressed by &lt;a href="https://youtu.be/AdNJ3fydeao" rel="noopener noreferrer"&gt;Rich Harris’s speech&lt;/a&gt; (It's worth a try even though it is an old one now). Svelte does the reactivity through the compiler and all of the heavy lifting has been done by the compiler.&lt;/p&gt;

&lt;p&gt;React Hooks vs Svelte, There is a lot more to discuss about it but for this article I’ll give you my perspective about two important aspects of the frameworks, better developer experience and better user experience.&lt;/p&gt;

&lt;h3&gt;
  
  
  Better developer experience
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Learning curve&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since Svelte tries to follow the web standard as much as possible, learning Svelte is very easy. As a javascript developer, it took just &lt;a href="https://youtu.be/rv3Yq-B8qp4" rel="noopener noreferrer"&gt;5 minutes to understand&lt;/a&gt; to get the basic idea, and a few hours to master all concepts. I’m that curious guy who always jumps into the underlying framework code before using it. It makes me more comfortable while coding. So I forked the svelte compiler code and used TanLiHau’s &lt;a href="https://lihautan.com/the-svelte-compiler-handbook/" rel="noopener noreferrer"&gt;compiler&lt;/a&gt; &lt;a href="https://lihautan.com/compile-svelte-in-your-head-part-2/" rel="noopener noreferrer"&gt;handbook&lt;/a&gt; to understand the compiler architecture. The whole process took a weekend to make myself comfortable. At the end of two days, I did some POCs like counter, todo lists, built a trello like app and a wrapper for &lt;a href="https://flatpickr.js.org/" rel="noopener noreferrer"&gt;flatpickr&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Although I knew the React class component well, it almost took a week to understand all the nuances of hooks like the why, where and how to use it effectively. This &lt;a href="https://the-guild.dev/blog/react-hooks-system" rel="noopener noreferrer"&gt;blog&lt;/a&gt; will help you to &lt;a href="https://eliav2.github.io/how-react-hooks-work/" rel="noopener noreferrer"&gt;learn&lt;/a&gt; more about the underlying hooks system.&lt;/p&gt;

&lt;p&gt;Apparently the Svelte learning curve was much smaller than React Hooks for me. With Svelte, any Javascript developer can learn the basic principles of a component state without getting confused by the details too much. Also &lt;a href="https://svelte.dev/tutorial/writable-stores" rel="noopener noreferrer"&gt;Svelte store&lt;/a&gt; is simpler to learn and use when compared to Redux/ React’s context API/useContext /Zustand or Jotai etc.,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Readability and Maintenance&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We have been using a lot of frameworks in our products. So readability and clarity are more important to me than any new fancy features.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” ― Martin Fowler&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;&lt;a href="https://codesandbox.io/s/react-hook-hell-g6kos?file=/src/App.js:0-1700" rel="noopener noreferrer"&gt;React Hook&lt;/a&gt; - sample code to capture mouse coordinates&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;em&gt;&lt;a href="https://svelte.dev/tutorial/inline-handlers" rel="noopener noreferrer"&gt;Svelte&lt;/a&gt; - sample code to capture mouse coordinates&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;blockquote&gt;
&lt;p&gt;“Let us forget about the number of lines of code that we needed to write. Assume you just know Javascript well, you are reading how to capture mouse coordinates during movement. Which code looks more like what you actually need?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As seen from above, Svelte does great things in a few lines of code. It's easier to read and understand by anyone who has some basic HTML/CSS/JS knowledge. It completely removes all of the unnecessary boilerplates like useState, useRef, useCallback, useMemo etc., from our application logic. Writing less code will help us with less maintenance and more time to develop new features. Read more about the readability part on &lt;a href="https://svelte.dev/blog/write-less-code" rel="noopener noreferrer"&gt;Rich Harris’s blog&lt;/a&gt;. On a side note:  If the same example was written using React class component, it would be way more readable than the one using Hooks.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;External library integration&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;React uses Virtual DOM so we need a special wrapper to handle the state of the external library components. But, the React community is extremely huge so you can find wrappers or equivalent React implementation easily. On the other hand, Svelte deals with the real DOM. This makes things simple and easy when doing some CSS Animations and DOM manipulations. You can use any DOM libraries directly or you can write a simple wrapper by yourself.&lt;/p&gt;

&lt;h3&gt;
  
  
  Better User experience
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Svelte surgically updates the DOM without relying on a middle interpreter or any complex reconciliation algorithm. It’s often beating out other frameworks on UI and &lt;a href="https://krausest.github.io/js-framework-benchmark/current.html" rel="noopener noreferrer"&gt;JS speed&lt;/a&gt;. And it’s increasingly used in production on various popular and traction heavy sites.&lt;/li&gt;
&lt;li&gt;React is fast enough to give a good user experience for the majority of use cases but when we have performance needs in terms of rendering, especially if we work around data visualization then it is not enough. &lt;a href="https://svelte.dev/blog/virtual-dom-is-pure-overhead" rel="noopener noreferrer"&gt;Virtual DOM is a pure overhead&lt;/a&gt;. It doesn’t matter how efficiently the diffing algorithm evolves; it will always eat up client’s hardware resources.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Doesn’t Svelte have any flaws?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The syntax used for component props is a bit weird for me.&lt;/li&gt;
&lt;li&gt;Svelte won’t listen for reference updates and array mutations, which developers need to actively look out for and make sure arrays are reassigned.&lt;/li&gt;
&lt;li&gt;Compared to Svelte, React has a huge community and you can easily find a &lt;a href="https://stackoverflow.com/questions/68291908/why-is-promise-then-called-twice-in-a-react-component-but-not-the-console-log" rel="noopener noreferrer"&gt;solution to any problem&lt;/a&gt;. As a React developer, I really like Svelte as well. However, I've only found Svelte useful in lightweight simple projects. I like Svelte API and reactivity out of the box, but for all its advantages, the ecosystem around svelte is lacking compared to react. To speed up development in a more complicated web app we need tools/libraries like &lt;a href="https://kit.svelte.dev/" rel="noopener noreferrer"&gt;svelte kit&lt;/a&gt;, svelte-query, svelte-yup etc., but these are not mature enough yet. Hopefully, Svelte's ecosystem will get better as more people start using it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;If you have Javascript knowledge and experience in other frameworks, you can adapt to Svelte quickly. Coding in &lt;a href="https://www.htmlallthethings.com/podcasts/svelte-is-here-to-stay" rel="noopener noreferrer"&gt;Svelte feels effortless&lt;/a&gt;, development time is also blazing fast when compared to React or many other frameworks.&lt;/li&gt;
&lt;li&gt;In my experience I observed that developers always find it difficult to switch from other frameworks to React Hooks. Trust me, I was a big fan of React hooks when it was introduced. I do like the idea of function components and hooks, but I certainly don’t enjoy working with them in a larger project.&lt;/li&gt;
&lt;li&gt;See the below history, &lt;a href="https://twitter.com/Rich_Harris/status/1421544403882160136" rel="noopener noreferrer"&gt;React&lt;/a&gt; &lt;a href="https://mobile.twitter.com/leeerob/status/1353523847937536000" rel="noopener noreferrer"&gt;keeps evolving&lt;/a&gt; but in the &lt;a href="https://mobile.twitter.com/dan_abramov/status/1191495127358935040" rel="noopener noreferrer"&gt;wrong direction&lt;/a&gt;, Svelte simply just chooses the right path.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1rp3zggih80eeqv3gi3k.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1rp3zggih80eeqv3gi3k.jpeg" alt="React State"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>svelte</category>
      <category>reacthooks</category>
      <category>reactvssvelte</category>
    </item>
  </channel>
</rss>
