<?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 Varun Vaibhav Jha on Medium]]></title>
        <description><![CDATA[Stories by Varun Vaibhav Jha on Medium]]></description>
        <link>https://medium.com/@varunvjha?source=rss-9fc4851ba164------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*92tAzm0o0r24xw8o6KpYFQ.png</url>
            <title>Stories by Varun Vaibhav Jha on Medium</title>
            <link>https://medium.com/@varunvjha?source=rss-9fc4851ba164------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 14:01:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varunvjha/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[Rester: Revolutionizing API Creation with No-Code Solutions]]></title>
            <link>https://blog.spense.money/rester-revolutionizing-api-creation-with-no-code-solutions-d4c3eba0d1b2?source=rss-9fc4851ba164------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4c3eba0d1b2</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Varun Vaibhav Jha]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 16:33:03 GMT</pubDate>
            <atom:updated>2023-12-02T16:33:03.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YXWD2qvaaeRZ4X4Q" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=medium&amp;utm_medium=referral">Adi Goldstein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In the fast-paced realm of software development, the demand for efficiency and simplicity is paramount. This is precisely where <strong>Rester</strong>, our innovative backend solution, enters the scene. <strong>Rester</strong> is a module tailored for Node.js environments, particularly leveraging Express.js, and is designed to transform the way APIs are created. It offers a no-code approach, allowing users to configure APIs through a database table. Let’s dive into the world of <strong>Rester</strong> and explore how it reshapes API development.</p><h4><strong>What is Rester?</strong></h4><p><strong>Rester</strong> is a cutting-edge module in the Node.js ecosystem. It streamlines API development, enabling the creation of endpoints through simple database configurations, thus eliminating the need for extensive backend coding. This approach is particularly beneficial for developers looking to rapidly deploy APIs without delving deep into code complexities.</p><h4><strong>The Core of Rester: Table Structure</strong></h4><p><strong>Rester</strong> operates on an elegantly simple table structure. This structure is the foundation upon which the module builds its functionality:</p><ol><li><strong>id</strong>: Primary key.</li><li><strong>slug</strong>: The endpoint’s slug, forming a part of the API’s URL.</li><li><strong>method</strong>: The HTTP method (GET, POST, PUT, etc.), defining the type of operation.</li><li><strong>query</strong>: The specific SQL query to be executed upon the API call.</li><li><strong>override</strong>: A JSON column for additional configuration settings. The values here can be used to override the some of the values sent in the request object.</li><li><strong>created_at</strong>: The creation timestamp for each entry.</li><li><strong>modified_at</strong>: Automatically updated timestamp upon any modification.</li></ol><p>This structured approach to API configuration promotes clarity and order, making API management a breeze.</p><h4><strong>Rester in Action: Detailed Code Breakdown</strong></h4><p>The core functionality of <strong>Rester</strong> is encapsulated in its code, which is both succinct and powerful. Let’s examine it in greater detail:</p><ul><li><strong>Router Setup</strong></li></ul><pre>const express = require(&quot;express&quot;); <br>const router = express.Router();</pre><blockquote>This snippet sets up an Express.js router, a fundamental step in handling API requests.</blockquote><ul><li><strong>Dynamic Endpoint Handling</strong></li></ul><pre>// Dynamically handles API requests based on configured slugs<br>router.all(&quot;/:slug&quot;, function (req, res, next) {<br>// Database Query Execution<br>  global.db<br>    .query(<br>      &quot;SELECT * FROM `Rester` WHERE `slug` = ? AND `method` = ? LIMIT 1;&quot;,<br>      [req.params.slug, req.method]<br>    )<br>    .then((result) =&gt; {<br>      if (result[0].length &lt; 1) {<br>        res.status(404).send({ message: &quot;API not found&quot;, type: &quot;danger&quot; });<br>      } else {<br>        // Given in the sections below<br>        // Adaptive Query Building here<br>      }<br>    })<br>    .catch((err) =&gt; {<br>      // Handle Error<br>    });<br>});</pre><blockquote>This is the code skeleton for efficiently capturing all types of HTTP requests for various slugs and processing further.</blockquote><ul><li><strong>Database Query Execution</strong></li></ul><pre>SELECT * FROM `Rester` WHERE `slug` = ? AND `method` = ? LIMIT 1;</pre><blockquote>It queries the <strong>Rester</strong> table to fetch the appropriate API configuration based on the request.</blockquote><ul><li><strong>Adaptive Query Building</strong></li></ul><pre>let query = result[0][0][&quot;query&quot;]; <br> // Code for replacing placeholders in the SQL query with request data<br>for (const i in replacer) {<br>  const replacerTerm = replacer[i][0];<br>  if (<br>    req.body.hasOwnProperty(<br>      replacerTerm.replace(&quot;{{&quot;, &quot;&quot;).replace(&quot;}}&quot;, &quot;&quot;)<br>    )<br>  ) {<br>      const replaceArray = req.body[<br>        replacerTerm.replace(&quot;{{&quot;, &quot;&quot;).replace(&quot;}}&quot;, &quot;&quot;)<br>      ]<br>        .toString()<br>        .split(&quot;,&quot;);<br>      for (const i in replaceArray) {<br>        replaceArray[i] = db.escape(replaceArray[i]);<br>      }<br>      query = query.replace(replacerTerm, replaceArray.join(&quot;,&quot;));<br>    } else if (<br>        req.query.hasOwnProperty(<br>          replacerTerm.replace(&quot;{{&quot;, &quot;&quot;).replace(&quot;}}&quot;, &quot;&quot;)<br>        )<br>    )  {<br>        const replaceArray = req.query[<br>          replacerTerm.replace(&quot;{{&quot;, &quot;&quot;).replace(&quot;}}&quot;, &quot;&quot;)<br>        ]<br>          .toString()<br>          .split(&quot;,&quot;);<br>        for (const i in replaceArray) {<br>          replaceArray[i] = db.escape(replaceArray[i]);<br>        }<br>        query = query.replace(replacerTerm, &quot;&quot; + replaceArray.join(&quot;,&quot;));<br>      } else if (<br>          req.params.hasOwnProperty(<br>            replacerTerm.replace(&quot;{{&quot;, &quot;&quot;).replace(&quot;}}&quot;, &quot;&quot;)<br>          )<br>      ) {<br>          const replaceArray = req.params[<br>            replacerTerm.replace(&quot;{{&quot;, &quot;&quot;).replace(&quot;}}&quot;, &quot;&quot;)<br>          ]<br>            .toString()<br>            .split(&quot;,&quot;);<br>          for (const i in replaceArray) {<br>            replaceArray[i] = db.escape(replaceArray[i]);<br>          }<br>          query = query.replace(replacerTerm, &quot;&quot; + replaceArray.join(&quot;,&quot;));<br>        }<br>      }</pre><blockquote>This segment dynamically adjusts the stored SQL query using data from the API request, enhancing flexibility, also used for replacing any placeholders in the query replacing with data from API request.</blockquote><ul><li><strong>Error Handling</strong></li></ul><pre>.catch((err) =&gt; {<br>  res.status(500).send({ message: &quot;Unable to run query&quot; });<br>});</pre><blockquote>Error handling ensures reliable API behavior under various scenarios. You can customize this as per your own needs.</blockquote><blockquote>Now, after following the above 5 steps, once setup correctly your own <strong>Rester</strong> framework is ready to start creating no-code APIs.</blockquote><h4><strong>Enhanced Features and Benefits</strong></h4><ul><li><strong>No-Code API Creation</strong>: Dramatically simplifies the process of setting up APIs.</li><li><strong>Flexibility</strong>: Compatible with various HTTP methods and complex SQL queries.</li><li><strong>Scalability</strong>: Facilitates easy addition of new APIs, making it ideal for growing projects.</li></ul><h4><strong>Best Practices and Advanced Considerations</strong></h4><ol><li><strong>Security with Prepared Statements</strong>: Vital for safeguarding against SQL injection attacks.</li><li><strong>Efficient Caching Mechanisms</strong>: Crucial for improving API response times and reducing database load.</li><li><strong>Detailed Logging Strategies</strong>: Key for effective debugging and maintaining operational integrity.</li><li><strong>Stringent Data Validation</strong>: Essential for ensuring the accuracy and appropriateness of incoming data.</li></ol><h4><strong>Conclusion</strong></h4><p><strong>Rester</strong> is not just a tool; it’s a paradigm shift in the realm of backend development, merging ease of use with powerful functionality. Its integration into your development process signifies a step towards more efficient, agile, and streamlined API management.</p><p><strong>Rester’s</strong> innovative approach to API creation marks a significant milestone in software development, enabling developers to focus more on the creative aspects of programming while it handles the complexities of API configurations. Adopting <strong>Rester</strong> could be your gateway to a more productive and efficient development experience.</p><p>For any doubts and suggestions, you can reach out to me on <a href="https://www.linkedin.com/in/varunvjha/">LinkedIn</a>. Happy Coding!</p><p>If you liked this story, do give it a 👏.</p><h3>Bringing Fintech to Life? Let’s Connect</h3><p><a href="https://spense.money/">Launch Your Fintech in a Month</a></p><p>At Spense, we are building the most advanced open banking platform ever, setting up secure and swift connections between banks and fintechs within minutes, not years. If you’re part of a fintech or planning to take your fintech idea off the ground, don’t hesitate to get in touch.</p><p>Are you in the fintech space or getting ready to launch your fintech venture? We’d love to connect with you and discover how we can make your journey easier. Schedule a time to chat with our expert through our Calendly and start the conversation.</p><p><a href="https://calendly.com/pawan-spense/30min?embed_domain=spense.money&amp;embed_type=Inline&amp;hide_landing_page_details=1&amp;hide_gdpr_banner=1&amp;back=1&amp;month=2023-12">Exploratory Call - Spense Founder&#39;s Office</a></p><p>For more about what we do, visit our <a href="https://spense.money/">website</a>. We look forward to learning about your project and contributing to your success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4c3eba0d1b2" width="1" height="1" alt=""><hr><p><a href="https://blog.spense.money/rester-revolutionizing-api-creation-with-no-code-solutions-d4c3eba0d1b2">Rester: Revolutionizing API Creation with No-Code Solutions</a> was originally published in <a href="https://blog.spense.money/">Spense Money</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Solution to Persistent Cookie Storage in Flutter]]></title>
            <link>https://blog.spense.money/a-solution-to-persistent-cookie-storage-in-flutter-8e70b14d8045?source=rss-9fc4851ba164------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e70b14d8045</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[cookies]]></category>
            <dc:creator><![CDATA[Varun Vaibhav Jha]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 12:39:38 GMT</pubDate>
            <atom:updated>2023-10-23T07:13:23.497Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>A Solution to Persistent Cookie Storage in Flutter: Shared Preferences Cookie Store Plugin</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAkS3QHgUUWVSoVg" /><figcaption>Photo by <a href="https://unsplash.com/@tvieso?utm_source=medium&amp;utm_medium=referral">Travis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>While developing applications with Flutter, one commonly faced challenge is managing persistent cookies. This becomes particularly tricky when dealing with HTTP clients like <a href="https://pub.dev/packages/dio"><strong>Dio</strong></a> and <a href="https://pub.dev/packages/dio_cookie_manager"><strong>DioCookieManager</strong></a><strong> </strong>as by default, cookies in Dio aren’t persistent across multiple sessions which means that if the app is closed and restarted, the cookies from the previous session are lost. The existing solutions out there, like the <strong>PersistCookieJar </strong>(provided by <a href="https://pub.dev/packages/cookie_jar"><strong>CookieJar</strong></a>) that provides FileStorage, were not meeting my specific use-case. So, creating my very own Flutter plugin — <strong>shared_prefs_cookie_store</strong> — became the inevitable solution.</p><h4><strong>The Challenge: Limitations of FileStorage</strong></h4><p>The standard approach in Flutter has been to utilize <strong>PersistCookieJar</strong> for cookie persistence. Here, <strong>FileStorage</strong> is implemented that saves cookies directly to the file system. Though reliable, few prominent limitations led me to seek an alternative.</p><ul><li><strong>Persistence beyond App Data Clearance:</strong> Cookies resident in FileStorage remain in the file system even after application data is cleared, which potentially poses a risk to user privacy.</li><li><strong>Complex Multiplatform Support:</strong> Different file system structures, permissions, and access methodologies, particularly in a multiplatform scenario of iOS and Android, instigate complexity.</li><li><strong>Restricted Customization:</strong> FileStorage does not offer the flexibility to select where the cookies are stored. Certain development scenarios may warrant storage of cookies in shared preferences or a database for better data accessibility and management.</li><li><strong>Potential for Data Loss:</strong> File system storage is more vulnerable to data loss due to reasons like operating system updates or device storage space issues.</li></ul><h4><strong>The Use Case: Tailored Cookie Management</strong></h4><p>The existing cookie management was not suiting our specific needs:</p><ul><li>We wanted a customizable way to store the cookies, specifically in SharedPreferences rather than a file system.</li><li>The persistent cookies had to be managed in a way where, clearing the application data automatically cleared the persistent cookies.</li><li>System to manage cookies which is well-organized and follows a clear pattern, easy to implement and understand and functions consistently across Android and iOS.Understanding the requirements, we understood the necessity of crafting an implementation that not only manages persistent cookies but also respects user privacy and offers developers more control.</li></ul><blockquote><em>Seeing this gap, our aim was to design a model to store cookies in SharedPreferences, maintaining persistence across multiple application sessions. However, the asynchronous nature of SharedPreferences presented a hurdle: </em>the first network request upon app reload was processed before SharedPreferences could load the saved cookies from the previous session<em>.</em></blockquote><h4><strong>The Journey Towards the Solution</strong></h4><p>Several strategies were attempted to overcome this problem:</p><ol><li><strong>Initializing SharedPreferences before app startup:</strong> Our first attempt was to preload SharedPreferences to ensure cookies were ready. However, this did not solve the issue.</li><li><strong>Sending a dummy request to prime CookieManager:</strong> We tried sending a dummy network request to ‘prime’ CookieManager for future requests. Yet, this too, did not produce the desired effect.</li><li><strong>Using a new CookieManager for each request:</strong> The next approach was to create a new instance of CookieManager for each network request. This also fell short in providing a suitable solution.</li></ol><h3><strong>SharedPrefsCookieStore: The Final Solution</strong></h3><p>With these insights, we created the <strong>shared_prefs_cookie_store</strong>. This Flutter plugin was designed to manage a <strong>Dio</strong> instance and cookie jar but only initialize them after <strong>SharedPreferences</strong> had fully loaded. This mechanism defers the first network request until the cookies can be asynchronously retrieved from SharedPreferences. Ensuring each request carries the necessary cookies from the very first network interaction.</p><h4><strong>Sharing the Solution</strong></h4><p>Having successfully tackled the problem, sharing this solution in the form of <strong>shared_prefs_cookie_store</strong> seemed the next logical step. We wish to help developers dealing with similar challenges in managing cookies with <strong>Dio</strong> and <strong>SharedPreferences</strong>. We’ve put the plugin through rigorous tests using Flutter’s testing framework to ensure its reliability. This guarantees the plugin will perform as expected in different applications and scenarios.</p><h4><strong>Example Implementation</strong></h4><p>Now let’s go ahead and see how we can leverage this plugin and use it for your own use case.</p><p>1. Adding the required dependencies to <em>pubspec.yaml</em></p><pre>dio: ^5.3.2<br>dio_cookie_manager: ^3.1.0+1<br>shared_prefs_cookie_store: ^0.0.2</pre><blockquote>Run <em>flutter pub get</em> from your terminal after adding these lines</blockquote><p>2. Now let’s go ahead and create a common class for Network Requests</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:dio_cookie_manager/dio_cookie_manager.dart&#39;;<br>import &#39;package:shared_prefs_cookie_store/shared_prefs_cookie_store.dart&#39;;<br><br>class APICall {<br>  final Dio _dio;<br><br>  static final APICall _instance = APICall._internal();<br>  final SharedPrefCookieStore _cookieStore = SharedPrefCookieStore();<br><br>  factory APICall() =&gt; _instance;<br><br>  APICall._internal() : _dio = Dio() {<br>    init();<br>  }<br><br>  void init() async {<br>    _dio.interceptors.add(CookieManager(_cookieStore));<br>    _dio.interceptors.add(<br>      InterceptorsWrapper(<br>        onRequest: (options, handler) {<br>          print(&#39;Sending request to ${options.uri}&#39;);<br>          return handler.next(options);<br>        },<br>        onResponse: (response, handler) {<br>          print(&#39;Received response: $response&#39;);<br>          return handler.next(response);<br>        },<br>        onError: (DioException error, handler) {<br>          print(&#39;Error occurred: $error&#39;);<br>          return handler.next(error);<br>        },<br>      ),<br>    );<br>  }<br><br>  void clearCookies() {<br>    _cookieStore.deleteAll();<br>  }<br><br>  Dio get client =&gt; _dio;<br>}</pre><blockquote>This is just an example class which I have created for demonstration purposes, your class to handle can differ and be much more comprehensive depending on your use cases.</blockquote><p>3. Create an example function to test the cookie store if it is working perfectly.</p><pre>Future&lt;void&gt; testCookieStore() async {<br>APICall apiCall = APICall();<br>  //Send a dummy request to your domain to prime DioCookieManager<br>  await apiCall.client.get(&quot;https://example.com&quot;);<br><br>  //Request which actually sets the cookies to the DioCookieManager<br>  await apiCall.client.get(&quot;https://example.com/set_cookies&quot;);<br><br>  //Any requests made after this will use these cookies<br><br>  //Request using cookies from DioCookieManager<br>  await apiCall.client.get(&quot;https://example.com/use_cookies&quot;);<br><br>  //Now let&#39;s clear all cookies<br>  apiCall.clearCookies();<br><br>  //Request using cookies from DioCookieManager<br>  await apiCall.client.get(&quot;https://example.com/use_cookies&quot;);<br>  //Response this time around will be different as there are no cookies<br>}</pre><h4><strong>Limitations of SharedPrefsCookieStore</strong></h4><p>While the plugin successfully bypasses the limitations of FileStorage, it comes with its own set of challenges:</p><ul><li><strong>Dependency on SharedPreferences</strong>: <strong>shared_prefs_cookie_store’s</strong> reliance on SharedPreferences means it’s subject to any future changes or limitations imposed on SharedPreferences by Flutter or the platform you’re developing on.</li><li><strong>Data Storage Considerations</strong>: SharedPreferences is ideal for storing small amounts of data. If an application deals with a high volume of large cookies or sets cookies too frequently, performance may be impacted.</li></ul><h4><strong>Performance Impact</strong></h4><p>In terms of latency and performance, <strong>shared_prefs_cookie_store</strong> exhibits comparable performance to traditional FileStorage methods. As SharedPreferences are efficient in accessing small amounts of data, and since cookies are light on memory, <strong>shared_prefs_cookie_store</strong> provides an effective method to handle cookies without significant performance overhead.</p><h4><strong>Conclusion</strong></h4><p>The experience of developing a remedy for persistent cookie management highlights the complexities involved in simple operations in Flutter development. It also emphasized the impact of asynchronous operations how data loading can be synchronized for a seamless application experience.</p><p><strong>shared_prefs_cookie_store</strong> can help developers tackle similar challenges efficiently while, at the same time holding user privacy and data management in high esteem. We sincerely wish that this exploration into solving a problem enhances the robustness of applications and contributes to the ever-evolving Flutter environment.</p><h3>Collaborate with Us</h3><p><a href="https://github.com/spense-fintech/shared_prefs_cookie_store">GitHub - spense-fintech/shared_prefs_cookie_store: This is a Flutter plugin for managing HTTP cookies, utilizing SharedPreferences for storage and ensuring cookie persistence.</a></p><p>Excited by what <strong>shared_prefs_cookie_store</strong> can do? We encourage you to contribute! Our work is open-source and we strive to make this tool even better with your help. Check out our GitHub repository and consider making a pull request. Whether it&#39;s improving documentation, adding features, or finding bugs, we appreciate all contributions.</p><p>For any doubts and suggestions, you can reach out to me on <a href="https://www.linkedin.com/in/varunvjha/">LinkedIn</a>. Happy Coding!</p><p>If you liked this story, do give it a 👏.</p><h4>Bringing Fintech to Life? Let’s Connect</h4><p><a href="https://spense.money/">Launch Your Fintech in a Month</a></p><p>At Spense, we are building the most advanced open banking platform ever, setting up secure and swift connections between banks and fintechs within minutes, not years. If you’re part of a fintech or planning to take your fintech idea off the ground, don’t hesitate to get in touch.</p><p>Are you in the fintech space or getting ready to launch your fintech venture? We’d love to connect with you and discover how we can make your journey easier. Schedule a time to chat with our expert through our Calendly and start the conversation.</p><p><a href="https://calendly.com/pawan-spense/30min?embed_domain=spense.money&amp;embed_type=Inline&amp;hide_landing_page_details=1&amp;hide_gdpr_banner=1&amp;back=1&amp;month=2023-10">Exploratory Call - Spense Founder&#39;s Office</a></p><p>For more about what we do, visit our <a href="https://spense.money/">website</a>. We look forward to learning about your project and contributing to your success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e70b14d8045" width="1" height="1" alt=""><hr><p><a href="https://blog.spense.money/a-solution-to-persistent-cookie-storage-in-flutter-8e70b14d8045">A Solution to Persistent Cookie Storage in Flutter</a> was originally published in <a href="https://blog.spense.money/">Spense Money</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discover Mysql Model Router — A Powerful Tool for API Development in Node.js]]></title>
            <link>https://blog.spense.money/discover-mysql-model-router-a-powerful-tool-for-api-development-in-node-js-38fdef415722?source=rss-9fc4851ba164------2</link>
            <guid isPermaLink="false">https://medium.com/p/38fdef415722</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Varun Vaibhav Jha]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 18:36:45 GMT</pubDate>
            <atom:updated>2023-10-18T05:00:49.714Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Discover MySQL Model Router — A Powerful Tool for API Development in Node.js</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0U6KmetZNKB2-YwL" /></figure><p>In the ever-evolving world of development, efficiency is king. An ongoing mission in every developer’s journey is the constant search for ways to simplify, automate, and speed up the process without compromising the quality of the produced result. The creation of Node.js was a significant leap in this journey, and the universe of npm modules further added to the vibrancy of this environment.</p><p>Today, I will share a gem from our own team — the <strong>mysql-model-router </strong>npm library that has been not less than a revelation in making our server-side code creation task easier and faster.</p><h3><strong>What is mysql-model-router?</strong></h3><p><a href="https://www.npmjs.com/package/mysql-model-router">mysql-model-router</a></p><p>It’s a powerful npm library that paves the path for generative API creation using the <a href="https://www.npmjs.com/package/mysql2">mysql2</a> and <a href="https://www.npmjs.com/package/express">express</a> libraries in node.js.</p><p>The <strong>mysql-model-router</strong> allows you to generate a full set of API endpoints with just a few lines of code. The syntax is straightforward — define your database connection, the data structure of your table, and the library will handle the rest.</p><h4><strong>Getting Started</strong></h4><p>To give you an idea of how it works, imagine wanting to create a simple API based on a ‘dim_user’ table in a MySQL database. Here’s what the code would look like using <strong>mysql-model-router</strong>:</p><pre>db.connect({<br>    connectionLimit: 100,<br>    host: process.env.DB_HOST,<br>    user: process.env.DB_USER,<br>    password: process.env.DB_PASS,<br>    database: process.env.DB_NAME,<br>    port: process.env.DB_PORT,<br>    charset: &quot;utf8mb4&quot;<br>}); //Example db connection<br> <br>let userModel = model(db,<br>    &quot;dim_user&quot;, <br>    {<br>        user_id: &quot;required|integer&quot;,<br>        name: &quot;required|string&quot;,<br>        email: &quot;required|string&quot;,<br>        phone: &quot;required|string&quot;,<br>        age: &quot;integer&quot;,<br>        password: &quot;required|string&quot;,<br>        info: &quot;object&quot;,<br>        is_deleted: &quot;boolean&quot;,<br>    }, //Table Structure<br>    &quot;user_id&quot;, //Primary key<br>    [&quot;phone&quot;], //Unique<br>    { safeDelete: &quot;is_deleted&quot; } <br>);<br> <br>app.use(&quot;/test&quot;, route(userModel));</pre><p>With this simple configuration, you can get a full fledge of endpoints like <strong>GET /:id</strong>, <strong>POST / </strong>(single object as input {…}), <strong>PUT /:id</strong> (single object as input {…}), <strong>DELETE /:id</strong>, and their bulk counterparts such as <strong>GET /, POST </strong>(it takes an array of objects as input in the form of data: [{…}, {…}])<strong> /, PUT / </strong>(it takes an array of objects as input in the form of data: [{…}, {…}]) <strong>and DELETE /</strong>. The library handles CRUD operations with ease and even supports conditional query parameters.</p><h4><strong>Safe Deletions</strong></h4><p>A <strong>safe delete (synonymous to soft delete) </strong>operation is a noteworthy feature in <strong>mysql-model-router</strong>. It marks a record as deleted rather than completely removing it from your database, thereby allowing data recovery when necessary. Enabling this feature is as simple as defining it in your model:</p><pre>{ safeDelete: &quot;is_deleted&quot; }</pre><h4><strong>Creating Custom Functions</strong></h4><p><strong>mysql-model-router</strong> allows you to add custom functions to your model. This feature becomes handy when you need a specialized query that is not included within the CRUD operations provided by model functions, you can override any of the conventional CRUD methods provided by the model or even create additional functions. Once you have created the custom functions, you can go ahead and create custom routes to use them as mentioned below this section. This feature promotes flexibility and eases the alignment to specific project requirements:</p><pre>userModel[&quot;byId&quot;] = async(id) =&gt; {<br>    // Custom query to fetch byId which is not the conventional approach<br>}</pre><h4><strong>Creating Custom Routes</strong></h4><p>When the auto-generated APIs aren’t enough, <strong>mysql-model-router</strong> has got you covered. This library allows you to define customized APIs using various model functions. These presets cover different operations such as <strong>insert</strong>, <strong>update</strong>, <strong>remove</strong>, <strong>find</strong>, and <strong>list</strong> actions.</p><p>Let’s take you have defined a schema for a basic user model. Now we’ll do deep dive into some examples of the <strong>mysql-model-router</strong> functions:</p><pre>const userModel = model(<br>    db,<br>    &quot;dim_user&quot;,<br>    {<br>        user_id: &quot;required|integer&quot;,<br>        name: &quot;required|string&quot;,<br>        email: &quot;required|string&quot;,<br>        phone: &quot;required|string&quot;,<br>        password: &quot;required|string&quot;,<br>        is_deleted: &quot;boolean&quot;,<br>    },<br>    &quot;user_id&quot;, // &quot;user_id&quot; is the primary key for the user model.<br>    [&quot;phone&quot;], // The array [&quot;phone&quot;] represents a unique composite key combination.<br>    { safeDelete: &quot;is_deleted&quot; }<br>);<br><br>// Inserting a new user<br>let newUser = {<br>    name: &quot;John Doe&quot;,<br>    email: &quot;johndoe@example.com&quot;,<br>    phone: &quot;9876543210&quot;,<br>    password: &quot;securepassword&quot;,<br>};<br>await userModel.insert(newUser);<br><br>// Updating a user&#39;s data<br>let updatedUser = {<br>    user_id: 1,<br>    name: &quot;John Updated&quot;,<br>    phone: &quot;0123456789&quot;,<br>    email: &quot;johnupdated@example.com&quot;,<br>};<br>await userModel.update(updatedUser);<br><br>// Upsert: Update if exists, otherwise insert<br>let upsertUser = {<br>    user_id: 1,<br>    name: &quot;John Upserted&quot;,<br>    phone: &quot;9876543210&quot;,<br>    email: &quot;johnupserted@example.com&quot;,<br>};<br>await userModel.upsert(upsertUser);<br><br>// Removing a user (safe delete)<br>await userModel.remove({ user_id: 1 });<br><br>// Retrieving a user by id<br>await userModel.byId(1);<br><br>// Finding users based on certain criteria<br>// Finding Users with user_id equal to 1:<br>let filter = [[[&quot;user_id&quot;, &quot;=&quot;, 1]]];<br>let result = await userModel.find(filter);<br><br>// Finding Users with user_id equal to 1 AND role is admin:<br>let filter = [[[&quot;user_id&quot;, &quot;=&quot;, 1], [&quot;role&quot;, &quot;=&quot;, &quot;admin&quot;]]];<br>let result = await userModel.find(filter);<br><br>// Finding Users with user_id equal to 1 OR role is admin:<br>let filter = [[[&quot;user_id&quot;, &quot;=&quot;, 1]], [[&quot;role&quot;, &quot;=&quot;, &quot;admin&quot;]]];<br>let result = await userModel.find(filter);<br><br>// Finding one user based on a search criteria (e.g. Name matching John) <br>// Will return the 1st record with search criteria matched<br>let userNamedJohn = await userModel.findOne({<br>    name: &quot;John&quot;,<br>});<br><br>// Listing users with pagination and sorting<br>let paginatedUsers = await userModel.list({<br>    page: 1,<br>    size: 20,<br>    filter: [],<br>    sort: [[&quot;name&quot;, &quot;ASC&quot;]],<br>});</pre><p>In the above example, I have just given a demo of <strong>filter</strong>. Let’s talk about filter in more detail below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oi7oFIfVpkEg_peX" /><figcaption>Photo by <a href="https://unsplash.com/@klosinski?utm_source=medium&amp;utm_medium=referral">Jacek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Filter</h4><p>In this library, the filter provides a comprehensive structure for managing complex queries. This structure utilizes nested arrays to represent and organize various conditions.</p><p>Every inner-most array represents a separate condition within the query. For example, each condition might be corresponding to a comparison like “price is greater than 20” or “category equals electronics”.</p><p>As you step out to the outer arrays, those collections of conditions get connected by logical operators, specifically AND and OR. For instance, if you want to find items that are in the “electronics” category AND cost more than 20, you will nest the individual conditions within an outer array, representing an AND relationship.</p><blockquote>In simpler terms, each array is a group of conditions. Inner arrays define standalone conditions, and outer arrays help to group and connect these conditions using logical operators. This flexible arrangement allows for the construction of detailed and complex database queries.</blockquote><p>Let’s break this down further:</p><p>A basic condition is written as [“column_name”, “operation”, “value”]. For example, to filter for users whose “user_id” is 1, you would use</p><pre>[&quot;user_id&quot;, &quot;=&quot;, 1]</pre><p>The operations you can use include:</p><ul><li>= for equals</li><li>like for the SQL LIKE statement</li><li>in for the SQL IN statement</li><li>&lt;, &gt;, &lt;=, &gt;= for less than, greater than, less than or equal, greater, or equal comparisons</li><li>!= for not equal</li></ul><p>Multiple conditions can be grouped together using an outer array to represent AND logic. For example, to filter for users whose user_id is 1 AND role is admin, you would use</p><pre>[[&quot;user_id&quot;, &quot;=&quot;, 1], [&quot;role&quot;, &quot;=&quot;, &quot;admin&quot;]]</pre><p>For OR logic, you can further nest these conditions within another array. For example, to filter for users who are either admins OR have a user_id of 1, you would use</p><pre>[[[&quot;user_id&quot;, &quot;=&quot;, 1]], [[&quot;role&quot;, &quot;=&quot;, &quot;admin&quot;]]]</pre><p>This format can help you build complex filter conditions according to the needs of your application.</p><h4><strong>Session-Aware Filtering</strong></h4><p>One of the more advanced features is the ability to create session-aware filters. With a simple override object supplied to the route function, we can filter data based on a user’s session information. This provides a personalized and secure view of data to each user. For example:</p><pre>route(userModel, {<br>    user_id: &quot;session.user.user_id&quot;<br>})</pre><h4><strong>Performance</strong></h4><p>Although <strong>mysql-model-router</strong> makes the workflow more user-friendly, it doesn’t trade-off performance. In fact, its performance is on par with other top-tier libraries or ORMs, and its ability to handle bulk operations is incredibly impressive, with speed about <strong>200x faster</strong> than conventional ORM. This exceptionally high speed for bulk operations adds a monumental advantage, especially when dealing with large datasets.</p><h4><strong>Final Thoughts</strong></h4><p>All in all, <strong>mysql-model-router</strong> has been a game-changer for us at Spense in terms of API creation in Node.js. It has streamlined our workflow, reduced boilerplate code, and made maintaining and expanding our API collection considerably more manageable. We’ve been able to shift our focus to creating robust and feature-rich applications in less time. If you are navigating the waters of backend development in Node.js, give <strong>mysql-model-router</strong> a shot. You’ll love the simplicity and speed it brings to your development process.</p><h4>Collaborate with Us</h4><p><a href="https://github.com/eforge-xyz/rest-router">GitHub - eforge-xyz/rest-router: Generative API Creation using mysql2 and express libraries in node js</a></p><p>Excited by what <strong>mysql-model-router</strong> can do? We encourage you to contribute! Our work is open-source and we strive to make this tool even better with your help. Check out our GitHub repository and consider making a pull request. Whether it&#39;s improving documentation, adding features, or finding bugs, we appreciate all contributions.</p><p>For any doubts and suggestions, you can reach out to me on <a href="https://www.linkedin.com/in/varunvjha/">LinkedIn</a>. Happy Coding!</p><p>If you liked this story, do give it a 👏.</p><h4>Bringing Fintech to Life? Let’s Connect</h4><p><a href="https://spense.money/">Launch Your Fintech in a Month</a></p><p>At Spense, we are building the most advanced open banking ever, setting up secure and swift connections between banks and fintechs within minutes, not years. If you’re part of a fintech or planning to take your fintech idea off the ground, don’t hesitate to get in touch.</p><p>Are you in the fintech space or getting ready to launch your fintech venture? We’d love to connect with you and discover how we can make your journey easier. Schedule a time to chat with our expert through our Calendly and start the conversation.</p><p><a href="https://calendly.com/pawan-spense/30min?embed_domain=spense.money&amp;embed_type=Inline&amp;hide_landing_page_details=1&amp;hide_gdpr_banner=1&amp;back=1&amp;month=2023-10">Exploratory Call - Spense Founder&#39;s Office</a></p><p>For more about what we do, visit our <a href="https://spense.money/">website</a>. We look forward to learning about your project and contributing to your success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38fdef415722" width="1" height="1" alt=""><hr><p><a href="https://blog.spense.money/discover-mysql-model-router-a-powerful-tool-for-api-development-in-node-js-38fdef415722">Discover Mysql Model Router — A Powerful Tool for API Development in Node.js</a> was originally published in <a href="https://blog.spense.money/">Spense Money</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>