<?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 Saksham Singh on Medium]]></title>
        <description><![CDATA[Stories by Saksham Singh on Medium]]></description>
        <link>https://medium.com/@singhsaksham?source=rss-db3721ffe2c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oWJJ1sTLyazUl-cc</url>
            <title>Stories by Saksham Singh on Medium</title>
            <link>https://medium.com/@singhsaksham?source=rss-db3721ffe2c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:20:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@singhsaksham/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[How The Trip I Dreaded Became the Most Beautiful One]]></title>
            <link>https://singhsaksham.medium.com/how-the-trip-i-dreaded-became-the-most-beautiful-one-371832b5f133?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/371832b5f133</guid>
            <category><![CDATA[rajasthan]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[udaipur]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[india]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 19:09:47 GMT</pubDate>
            <atom:updated>2025-03-19T19:15:40.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJYktgt-7kGs5G8FDZmmhQ.jpeg" /></figure><p>Back in January 2023, my friends and I decided to visit Jaipur and Udaipur. I had been to Jaipur quite a few times before and had already visited the spots on our itinerary. In fact, my profile picture is still me at Jantar Mantar… from 2013. At this point, even Jaipur has changed more than my DP. 😆</p><p>However, this trip was with friends, I knew it would be fun.</p><p>I had no idea about Udaipur except that it is called ‘The City of Lakes.’ Like most of us, I searched online to find some popular must-visit tourist spots. However, the search results didn’t intrigue me much. I felt the lakes there would be like any other lakes I had been to before, the gardens wouldn’t offer anything new compared to the ones I had already seen, and the City Palace would be similar to Jaipur’s.</p><p>For these reasons, I did not have high expectations for Udaipur. I thought it would be boring compared to Jaipur and, hence, dreaded going there.</p><p>Little did I know how wrong I would be.</p><p>After an extensive two-day travel in Jaipur we took a train to Udaipur at night. It took us roughly eight hours to reach Udaipur. We started searching for hotel as soon as we reached there. After failing to find a decent one online, luckily, a cab driver at the station came to our rescue. He told us about a hotel nearby suitable for us.</p><p>We went with the cab driver, booked two rooms and it was a really nice stay for one day - that too for a reasonable price.</p><p>Since it was still 7 AM in the morning and no tourist places were open at that time, we decided to rest for a while and start our itinerary after 10 AM.</p><p>At first we went to the Fateh Sagar Lake and it was something I had never seen before. The crystal-clear water, the cool morning breeze, and the breathtaking reflection of the bright blue sky on the lake’s surface — it was truly mesmerizing. Boating in such a clear lake was an experience like no other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kboPOBNHlyDe-DGcdIIjpg.jpeg" /><figcaption>Some pics from the Fateh Sagar Lake</figcaption></figure><p>Next, we visited Saheliyon Ki Bari. According to Google, it is a beautiful garden with lush greenery and fountains and indeed, it was the most beautiful garden I’ve ever seen. The peaceful atmosphere and looking at the beautiful flowers made walking through it a truly memorable experience. There was also a small history museum here, which I causally ignored (I don’t like museums😂) .</p><p>One factor that made a huge difference, I believe, was the pleasant weather. Unlike the extreme summers or winters, the weather in January was mild and comfortable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uaxy-hly7b9hfTCgwB5ecg.jpeg" /></figure><p>Our next stop was the City Palace. However, since Lake Pichola was nearby, we decided to visit it first. It looked even more stunning than Fateh Sagar. We spotted a palace in the middle of the lake and learned that it was the famous ‘Taj Lake Palace.’ Due to time constraints, we skipped the boat ride, took some beautiful photos, and then proceeded to the City Palace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgLiwwnHUbtT8r2C7JSPIg.jpeg" /><figcaption>Lake Pichola</figcaption></figure><p>The City Palace of Udaipur seemed more magical than the palace I had seen in Jaipur. Situated on a hill, it provides bird’s eye views of Lake Pichola and the city below. The architecture of the palace is an elegant mixture of Rajasthani and Mughal influences, with exquisite mirror work and fine mosaics- at least, that’s the bit of history I managed to remember before getting distracted by photo ops. History ain’t one of my strongest skills😅</p><p>In the evening, we visited an aquarium called ‘Under the Sea’ located near Fateh Sagar Lake. It’s a fun place to visit with family and friends—where you can play VR games, explore different types of fish, and share laughs together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vw3hJCOogImBqq3D" /><figcaption><em>Fateh Sagar at night</em></figcaption></figure><p>After stepping out of the aquarium, we saw a group of people sitting on a bench and singing. Soon, other tourists, including us, gathered around them and joined in. As we walked back to our hotel, the whole moment felt straight out of a Bollywood movie—people singing in the background, a cool breeze, and the beautiful surroundings. As we walked by the lake, we visited an ice cream store. It featured a Turkish variation — wherein the seller plays with you first before giving the ice cream — to at a third of the price .</p><p>So many beautiful scenes and memories captured in a single day.</p><p>On our final day in Udaipur, we decided to visit the Monsoon Palace, also known as Sajjan Garh Palace. After buying our tickets, on a whim, we thought about trekking to the palace instead of taking a cab. FYI, the palace is 7 kilometers uphill from the ticket counter.</p><p>On our way up, we didn’t see anyone else trekking—only cars (either cabs or self-driven) and signboards warning about wild animals. At that moment, we realized two things: one, we might be the only ones who thought this was a great idea, and two, if a leopard showed up, our survival plan was just to outrun each other.</p><p>After an hour of walking and taking breaks—to rest and click photos—we finally reached the Monsoon Palace. Our first stop was a restaurant, where we ordered food and drinks to recharge. Then, we finally headed to explore the palace.</p><p>Considering how beautiful Udaipur was on day one, we had high expectations for the Monsoon Palace. To our surprise, it wasn’t all that amazing—we felt the trek wasn’t really worth it.</p><p>That said, the view from the top was stunning, and it’s a great spot for clicking some nice photos.</p><p>Trekking downhill was relatively easier. By the time we reached the entry point, we saw a few people starting the same trek—one that we had earlier considered quite foolish. Guess we weren’t the only ones with adventurous instincts!</p><p>Despite an underwhelming day two, day one’s memories made Udaipur one of the most beautiful places I’ve been to - if not the most.</p><p>It’s funny how the trip I once hesitated to take ended up creating such unforgettable memories.</p><p>Sometimes, the most beautiful events occur when we least expect them 😆</p><p>This is my first time writing about a travel experience — I hope you found it worth reading😅</p><p>If you have any suggestions, let me know in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=371832b5f133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TrailXpress: The Next Evolution After RoutesExplorer]]></title>
            <link>https://singhsaksham.medium.com/trailxpress-the-next-evolution-after-routesexplorer-8babd21a6914?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8babd21a6914</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 09:15:25 GMT</pubDate>
            <atom:updated>2025-02-28T09:15:25.412Z</atom:updated>
            <content:encoded><![CDATA[<h3>TrailXpress: The Next Evolution After Routes-Explorer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KWOrjIKO-lIstO1i" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa?utm_source=medium&amp;utm_medium=referral">Arnold Francisca</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A while ago, I created Routes-Explorer to help developers extract and visualize Express routes effortlessly. While it served its purpose, I saw opportunities for improvement so I built TrailXpress.</p><p>Routes-Explorer is no longer maintained, and all future development will continue under <strong>TrailXpress</strong>. If you were using Routes-Explorer, I highly recommend switching over.</p><p>You can install it from here: <a href="https://www.npmjs.com/package/trailxpress">https://www.npmjs.com/package/trailxpress</a></p><p>GitHub link: <a href="https://github.com/Saksham294/trailxpress">https://github.com/Saksham294/trailxpress</a></p><h3>Usage</h3><h4>Installation</h4><pre>npm install trailxpress</pre><p>To use this package, include it in your Node.js project and call the getRoutes function with the path to your Express API file.</p><pre>const { getRoutes } = require(&#39;trailxpress&#39;);</pre><pre>const apiFilePath = &#39;path/to/your/api/file.js&#39;;<br>try {<br>  const routes = getRoutes(apiFilePath);<br>  console.log(&#39;Extracted Routes:&#39;, routes);<br>} catch (error) {<br>  console.error(&#39;Error:&#39;, error.message);<br>}</pre><h4>Filtering Routes by HTTP Method</h4><p>You can filter routes based on request types (GET, POST, PUT, DELETE, etc.).</p><pre>const { getRoutes } = require(&#39;trailxpress&#39;);</pre><pre>const apiFilePath = &#39;path/to/your/api/file.js&#39;;<br>const filteredRoutes = getRoutes(apiFilePath, [&#39;GET&#39;, &#39;POST&#39;]); // Only fetch GET and POST routes<br>console.log(filteredRoutes);</pre><h4>Swagger Documentation Generation</h4><p>TrailXpress can generate Swagger documentation for your API.</p><pre>const { generateSwagger } = require(&#39;trailxpress&#39;);</pre><pre>const apiFilePath = &#39;path/to/your/api/file.js&#39;;<br>const routes = getRoutes(apiFilePath);<br>const swaggerDocs = generateSwagger(routes);<br>console.log(swaggerDocs);</pre><p>I have some plans to further improve TrailXpress. If you face any issues, have suggestions or feature request, you can comment below or raise an issue <a href="https://github.com/Saksham294/trailxpress/issues">here</a>.</p><p>If you found it useful you can star it too (it means a lot :D )</p><p>I’d love to hear your feedback and learn how TrailXpress can be improved to enhance your developer experience.</p><p>Hope you found it helpful.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8babd21a6914" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Published My First NPM Package: Here’s What Routes Explorer Does]]></title>
            <link>https://singhsaksham.medium.com/i-published-my-first-npm-package-heres-what-routes-explorer-does-ba071c47082b?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba071c47082b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 11:57:34 GMT</pubDate>
            <atom:updated>2024-10-10T11:57:34.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S0BvFF9kjcz3gjji" /><figcaption>Photo by <a href="https://unsplash.com/@pinjasaur?utm_source=medium&amp;utm_medium=referral">Paul Esch-Laurent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous <a href="https://medium.com/@sakshamsingh5001/how-to-extract-api-routes-using-javascript-babel-parser-and-ast-a-step-by-step-guide-ce846c5e590c">article</a>, I discussed a challenging problem I encountered and how I solved it.</p><p>The problem was to extract each route’s method, path and function body from an API, store them in an array and send it to the LLM.</p><p>I used Abstract Syntax Trees(AST) parser to solve it. If you want to read more about my approach you can refer to that article <a href="https://medium.com/@sakshamsingh5001/how-to-extract-api-routes-using-javascript-babel-parser-and-ast-a-step-by-step-guide-ce846c5e590c">here</a>.</p><p>Since that article was quite detailed, I understand not everyone may want to dive in deeply. To simplify things and provide a straightforward solution, I created an NPM package few months ago. You can easily install and use it to get the desired results without the hassle.</p><h4>Installation</h4><p>Copy the following command and paste it in your terminal</p><pre>npm install routes-explorer</pre><h4>Usage</h4><p>Import the <strong>getRouterAndRoutes</strong> function from the <em>routes-explorer</em> package, specify the path to your API and call the function as shown below</p><pre>const { getRouterAndRoutes } = require(&#39;routes-explorer&#39;);<br><br>const apiFilePath = &#39;path/to/your/api/file.js&#39;;<br><br>try {<br>  const { routerVariableName, routes } = getRouterAndRoutes(apiFilePath);<br>  console.log(&#39;Router Variable Name:&#39;, routerVariableName);<br>  console.log(&#39;Routes:&#39;, routes);<br>} catch (error) {<br>  console.error(&#39;Error:&#39;, error.message);<br>}</pre><p>You will get all your details in the <em>routes</em> array.</p><p>Since this is my first package, there may be some errors or edge cases. You can post them on the GitHub issues page here: <a href="https://github.com/Saksham294/routes-explorer">https://github.com/Saksham294/routes-explorer</a></p><p>If you found it useful you can star it too (it means a lot :D )</p><p>Hope you found it helpful.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba071c47082b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extract API Routes Using JavaScript Babel Parser and AST: A Step-by-Step Guide]]></title>
            <link>https://singhsaksham.medium.com/how-to-extract-api-routes-using-javascript-babel-parser-and-ast-a-step-by-step-guide-ce846c5e590c?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce846c5e590c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Sun, 26 May 2024 14:56:48 GMT</pubDate>
            <atom:updated>2026-05-02T03:48:12.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFiYtYHUZC0_5oTV" /><figcaption>Photo by <a href="https://unsplash.com/@jasonstrull?utm_source=medium&amp;utm_medium=referral">Jason Strull</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I was recently working on an interesting project where I had to feed API data to a LLM. The API had routes from which I had to extract each route’s method, path and function body, store them in an array and send it to the LLM.</p><p>At first it felt really daunting considering the task and the deadline. I had no idea about Abstract Syntax Trees and how they can be used to solve this problem. I searched over the Internet and found very few relevant articles for my use case. I used ChatGPT and though it did give me a good starting point, I had to search and do multiple iterations of the code I had written to get the desired results.</p><p>No worries if you don’t understand anything right now. By the end of this article I assure you’ll learn something new and interesting in an easy manner. You won’t have to struggle like I did; instead, you’ll gain valuable insights.</p><p>What we’ll cover</p><blockquote>1.What are Abstract Syntax Trees(AST)?</blockquote><blockquote>2.What is Babel Parser?</blockquote><blockquote>3.Coding</blockquote><h3>What are Abstract Syntax Trees?</h3><p>Consider the following code:</p><pre> while (b !== 0) {<br>     if (a &gt; b) {<br>         a = a - b;<br>      } else {<br>         b = b - a;<br>      }<br>  }<br> return a;</pre><p>As a programmer, you know what the above code does — it simply computes the greatest common divisor of two numbers, a and b. But how does the computer know what code you have written, what it does, where the while loop starts and ends, what type of computation needs to be carried out, and what variables are used?</p><p>When you write and send this code to a compiler or interpreter, it utilizes the Abstract Syntax Tree (AST) to understand the code structure. The AST helps in converting the code into assembly language for execution.</p><p>An Abstract Syntax Tree (AST) is like a roadmap for computer programs. It organizes code into a tree structure, showing how different parts relate to each other.</p><h3>What is Babel Parser?</h3><p>Babel is a toolset primarily used to transform ECMAScript 2015+ code into a version of JavaScript that is compatible with both modern and older browsers or environments.</p><p>Babel parser is a component of the Babel toolchain that is responsible for parsing JavaScript code into an Abstract Syntax Tree (AST). This AST serves as a structured representation of the code’s syntax, allowing Babel to analyze, transform, and generate code effectively.</p><p>Basically we’ll convert our code into an AST using Babel Parser. Once converted we can use that AST to manipulate and extract our desired data.</p><h3>Coding</h3><p>Warning: This will be a bit longer one</p><p>There can be two cases while writing an API</p><ol><li>Functions are present in the same file as the routes</li><li>Functions are present in a different file</li></ol><p>Our code will cover both the cases.</p><p>Here is a sample Express API I have created</p><p><em>api.js</em></p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const router = express.Router();<br>import { getAbout,getHello } from &#39;./functions.js&#39;;<br><br><br>router.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;hello world&#39;);<br>});<br><br>router.get(&#39;/about&#39;, getAbout);<br><br>router.post(&#39;/login&#39;, (req, res) =&gt; {<br>  res.send(&#39;hello world&#39;);<br>});<br><br>router.delete(&#39;/delete&#39;, (req, res) =&gt; {<br>  res.send(&#39;hello world&#39;);<br>});<br><br>router.get(&#39;/hello&#39;, getHello);</pre><p>As you can see some routes have their function bodies in the same file, but some not. Two routes have their function bodies in a different file</p><p><em>functions.js</em></p><pre>export const getAbout= (req, res) =&gt; {<br>    console.log(&#39;hello about&#39;);<br>}<br><br><br>export const getHello= (req, res) =&gt; {<br>    console.log(&#39;hello Hello&#39;);<br>}</pre><p>Now let us start creating our file<em> parser.js</em></p><p>Install these dependencies</p><pre>npm i @babel/parser @babel/traverse @babel/generator</pre><p>Import the required dependencies</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const babelParser = require(&#39;@babel/parser&#39;);<br>const traverse = require(&#39;@babel/traverse&#39;).default;<br>const generate = require(&#39;@babel/generator&#39;).default;</pre><p>We first need to define the path to our api.js file and read the code from that file to convert the source code into an AST</p><pre>const apiFilePath = path.join(__dirname, &#39;api.js&#39;);<br>const apiCode = fs.readFileSync(apiFilePath, &#39;utf-8&#39;);<br>const apiAst = babelParser.parse(apiCode, {<br>  sourceType: &#39;module&#39;,<br>  plugins: [&#39;jsx&#39;, &#39;typescript&#39;, &#39;dynamicImport&#39;],<br>});</pre><p>In the above code we first define the path to our api.js and read the source code in apiCode. The babelParser then coverts the source code in apiCode into an AST. The sourceType param tells the parser to treat the source code as ECMAScript module. The plugins help the parser to understand various types of codes, in this case-jsx,typescript,etc.</p><p>Now we will generate the AST for the functions.js file</p><pre>const functionsFilePath = path.join(__dirname, &#39;functions.js&#39;);<br>const functionsCode = fs.readFileSync(functionsFilePath, &#39;utf-8&#39;);<br>const functionsAst = babelParser.parse(functionsCode, {<br>  sourceType: &#39;module&#39;,<br>  plugins: [&#39;jsx&#39;, &#39;typescript&#39;, &#39;dynamicImport&#39;],<br>})<br></pre><p>I have directly specified the path to <em>functions.js</em>, however you can retrieve the path of imported functions from the AST generated from the API. Now let’s extract the imported functions</p><pre>//Helper function to extract code<br>function extractFunctionCode(node) {<br>  return generate(node).code;<br>}</pre><p>Now I’ll write some code and explain afterwards</p><pre>traverse(functionsAst, {<br>  ExportNamedDeclaration(path) {<br>    if (path.node.declaration &amp;&amp; path.node.declaration.type === &#39;FunctionDeclaration&#39;) {<br>      const functionName = path.node.declaration.id.name;<br>      const functionCode = extractFunctionCode(path.node.declaration);<br>      functionDefinitions[functionName] = functionCode;<br>    } else if (path.node.declaration &amp;&amp; path.node.declaration.type === &#39;VariableDeclaration&#39;) {<br>      const declarations = path.node.declaration.declarations;<br>      declarations.forEach((declaration) =&gt; {<br>        if (declaration.id &amp;&amp; declaration.init &amp;&amp; (declaration.init.type === &#39;ArrowFunctionExpression&#39; || declaration.init.type === &#39;FunctionExpression&#39;)) {<br>          const functionName = declaration.id.name;<br>          const functionCode = extractFunctionCode(declaration.init);<br>          functionDefinitions[functionName] = functionCode;<br>        }<br>      });<br>    }<br>  },<br>});</pre><p>We call the traverse function on the AST which will traverse each node and help us find our desired details. There are many types of nodes present in the tree, however in this case we are interested in those which have an export declaration. If you remember our functions.js file both of our functions are being exported, so it is easy to identify them using this type declaration.</p><p>Basically every time our traversal encounters an export declaration we are interested to find if it has our desired data or not.</p><p>Now you can declare functions using a variable declaration or a explicitly mentioning ‘function’ in front of your function name. We will account for both the cases.</p><p>We check if the node we are at has a function declaration or a variable declaration.</p><p>Let’s understand each piece of code one by one -</p><p>(path.node.declaration &amp;&amp; path.node.declaration.type === &#39;FunctionDeclaration&#39;): This checks if the current export is a function declaration (e.g., export function myFunction() {}</p><p>If true, we extract the function name and the function body and store in our array functionDefinitions.</p><p>Next we check if the function declaration type is done using a variable.</p><p>(path.node.declaration &amp;&amp; path.node.declaration.type === &#39;VariableDeclaration&#39;): This checks if the current export is a variable declaration (e.g., export const myFunction = () =&gt; {} )</p><p>const declarations = path.node.declaration.declarations;: Gets the list of variable declarations.</p><p>Next for every declaration we iterate and check if it is the one we are looking for. The functions declared through variables can be of two types</p><ol><li>Function expression</li><li>Arrow Functions</li></ol><p>(declaration.id &amp;&amp; declaration.init &amp;&amp; (declaration.init.type === &#39;ArrowFunctionExpression&#39; || declaration.init.type === &#39;FunctionExpression&#39;)): This code checks if the variable is initialized with an arrow function or a function expression.</p><p>Using similar logic as in ‘FunctionDeclaration’ we extract the desired function codes</p><p>After this traversal you can print the results in your console and it would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*hoZdIEPGVpsnS-oFUPfbyA.png" /></figure><p>Now let us extract routes from the api.js. For this we will use the AST generated from the api.js.</p><p>This will be a bit long, so I will explain it step by step.</p><p>How do we know where the HTTP methods and their function bodies and paths are defined?</p><p>In express APIs we usually import the express.Router() module and assign it to a variable. This is the router variable name. All the API routes will be defined using the this variable name.</p><p>In our case, the router variable name is router. So it is better to extract the this variable name and then use it to find which all statements start with that variable name. This will in turn help us find our required details.</p><p>Let’s find that router variable name first</p><pre>let routerVariableName;</pre><p>To find this variable name we’ll use our <em>apiAst</em> which was created from the api.js file</p><pre>traverse(apiAST,{<br> VariableDeclaration(path) {<br>    const declarations = path.get(&#39;declarations&#39;);<br>    declarations.forEach((declaration) =&gt; {<br>      if (<br>        declaration.get(&#39;init&#39;).isCallExpression() &amp;&amp;<br>        declaration.get(&#39;init.callee&#39;).isMemberExpression() &amp;&amp;<br>        declaration.get(&#39;init.callee.property&#39;).isIdentifier({ name: &#39;Router&#39; })<br>      ) {<br>        routerVariableName = declaration.get(&#39;id.name&#39;).node;<br>      }<br>    });<br>  },<br>})</pre><p>Here we look for nodes which are of type VariableDeclaration.</p><p>const declarations = path.get(&#39;declarations&#39;): This retrieves the list of variable declarations from the current VariableDeclaration node.</p><p>We loop over each declaration and try to find which declaration has Router in its statement. If found we get the name of that variable and assign it to routerVariableName.</p><p>Now we traverse the AST and find all the expressions which contain this routerVariableName. If those expressions contain our desired properties we simply extract those properties and store them in our routes array.</p><pre>let routes=[]<br>traverse(apiAst,{<br>CallExpression(path) {<br>    if (<br>      path.get(&#39;callee&#39;).isMemberExpression() &amp;&amp;<br>      path.get(&#39;callee.object&#39;).isIdentifier({ name: routerVariableName })<br>    ) {<br>      const method = path.get(&#39;callee.property&#39;).node.name;<br>      const routePath = path.get(&#39;arguments.0&#39;).node.value;<br>      const routeFunctionNode = path.get(&#39;arguments.1&#39;);<br><br>      if (routeFunctionNode.isIdentifier()) {<br>        const functionName = routeFunctionNode.node.name;<br>        const routeFunctionCode = importedFunctions[functionName] || functionDefinitions[functionName];<br>        if (routeFunctionCode) {<br>          routes.push({ method, path: routePath, functionCode: routeFunctionCode });<br>        }<br>      } else if (routeFunctionNode.isArrowFunctionExpression() || routeFunctionNode.isFunctionExpression()) {<br>        const routeFunctionCode = extractFunctionCode(routeFunctionNode.node);<br>        routes.push({ method, path: routePath, functionCode: routeFunctionCode });<br>      }<br>    }<br>  },<br>})</pre><p>While traversing the AST we check if we encounter any node of the type CallExpression. If so , we are interested in it.</p><p>path.get(&#39;callee&#39;).isMemberExpression(): Checks if the callee of the call expression is a member expression</p><p>path.get(&#39;callee.object&#39;).isIdentifier({ name: routerVariableName }): Checks if the object part of the member expression is an identifier with the name stored in routerVariableName</p><p>If both of the above conditions are true we have found our required expression.</p><p>Now we extract our desired properties from it.</p><p>const method = path.get(&#39;callee.property&#39;).node.name : Extracts the method</p><p>const routePath = path.get(&#39;arguments.0&#39;).node.value: Extracts the route path</p><p>const routeFunctionNode = path.get(&#39;arguments.1&#39;): Extract the function handle associated with that route.</p><p>There can be three types of function declarations within this route- identifier, arrow function or function expression.</p><p>Now we check if the routeFunctionNode is an identifier (e.g., router.get(&#39;/path&#39;, handlerFunction)) or an arrow function (e.g. router.get(‘/path’, () =&gt; { … })) or function expression.</p><p>For all types we extract the required data i.e. method,function body and path and store them in our routes array.</p><p>This process is repeated for all nodes which match our conditions and at last we get all the data from the API.</p><p>Let’s put all code together in one place</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const babelParser = require(&#39;@babel/parser&#39;);<br>const traverse = require(&#39;@babel/traverse&#39;).default;<br>const generate = require(&#39;@babel/generator&#39;).default;<br><br><br>const apiFilePath = path.join(__dirname, &#39;api.js&#39;);<br>const apiCode = fs.readFileSync(apiFilePath, &#39;utf-8&#39;);<br>const apiAst = babelParser.parse(apiCode, {<br>  sourceType: &#39;module&#39;,<br>  plugins: [&#39;jsx&#39;, &#39;typescript&#39;, &#39;dynamicImport&#39;],<br>});<br><br>// Read the code from functions.js<br>const functionsFilePath = path.join(__dirname, &#39;functions.js&#39;);<br>const functionsCode = fs.readFileSync(functionsFilePath, &#39;utf-8&#39;);<br>const functionsAst = babelParser.parse(functionsCode, {<br>  sourceType: &#39;module&#39;,<br>  plugins: [&#39;jsx&#39;, &#39;typescript&#39;, &#39;dynamicImport&#39;],<br>});<br><br>let routerVariableName;<br>const routes = [];<br><br>// Helper function to extract function <br>function extractFunctionCode(node) {<br>  return generate(node).code;<br>}<br><br>// Traverse the functions AST to get function definitions<br>const functionDefinitions = {};<br>traverse(functionsAst, {<br>  ExportNamedDeclaration(path) {<br>    if (path.node.declaration &amp;&amp; path.node.declaration.type === &#39;FunctionDeclaration&#39;) {<br>      const functionName = path.node.declaration.id.name;<br>      const functionCode = extractFunctionCode(path.node.declaration);<br>      functionDefinitions[functionName] = functionCode;<br>    } else if (path.node.declaration &amp;&amp; path.node.declaration.type === &#39;VariableDeclaration&#39;) {<br>      const declarations = path.node.declaration.declarations;<br>      declarations.forEach((declaration) =&gt; {<br>        if (declaration.id &amp;&amp; declaration.init &amp;&amp; (declaration.init.type === &#39;ArrowFunctionExpression&#39; || declaration.init.type === &#39;FunctionExpression&#39;)) {<br>          const functionName = declaration.id.name;<br>          const functionCode = extractFunctionCode(declaration.init);<br>          functionDefinitions[functionName] = functionCode;<br>        }<br>      });<br>    }<br>  },<br>});<br><br>const importedFunctions = {};<br><br>// Traverse the API AST to gather imported functions<br>traverse(apiAst, {<br>  VariableDeclaration(path) {<br>    const declarations = path.get(&#39;declarations&#39;);<br>    declarations.forEach((declaration) =&gt; {<br>      if (<br>        declaration.get(&#39;init&#39;).isCallExpression() &amp;&amp;<br>        declaration.get(&#39;init.callee&#39;).isMemberExpression() &amp;&amp;<br>        declaration.get(&#39;init.callee.property&#39;).isIdentifier({ name: &#39;Router&#39; })<br>      ) {<br>        routerVariableName = declaration.get(&#39;id.name&#39;).node;<br>      }<br>    });<br>  },<br>  CallExpression(path) {<br>    if (<br>      path.get(&#39;callee&#39;).isMemberExpression() &amp;&amp;<br>      path.get(&#39;callee.object&#39;).isIdentifier({ name: routerVariableName })<br>    ) {<br>      const method = path.get(&#39;callee.property&#39;).node.name;<br>      const routePath = path.get(&#39;arguments.0&#39;).node.value;<br>      const routeFunctionNode = path.get(&#39;arguments.1&#39;);<br><br>      if (routeFunctionNode.isIdentifier()) {<br>        const functionName = routeFunctionNode.node.name;<br>        const routeFunctionCode = importedFunctions[functionName] || functionDefinitions[functionName];<br>        if (routeFunctionCode) {<br>          routes.push({ method, path: routePath, functionCode: routeFunctionCode });<br>        }<br>      } else if (routeFunctionNode.isArrowFunctionExpression() || routeFunctionNode.isFunctionExpression()) {<br>        const routeFunctionCode = extractFunctionCode(routeFunctionNode.node);<br>        routes.push({ method, path: routePath, functionCode: routeFunctionCode });<br>      }<br>    }<br>  },<br>});<br><br>console.log(&#39;Router Variable Name:&#39;, routerVariableName);<br>console.log(&#39;Routes:&#39;, routes);</pre><p><em>output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StWB3E9nJxxZgsaLfUFBXA.png" /></figure><p>Voila! We have retrieved HTTP routes and their respective methods,path, and function bodies.</p><p>I know this article is pretty long, but it took me much longer to create this code when I was working on my project.</p><p>Hope you found it helpful.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce846c5e590c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate cURL commands using Postman Collection and OpenAPI spec]]></title>
            <link>https://singhsaksham.medium.com/generate-curl-commands-using-postman-collection-and-openapi-spec-0341234172fd?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0341234172fd</guid>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 05:49:47 GMT</pubDate>
            <atom:updated>2024-04-07T05:49:47.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAAAbaJrS4bqZ_BtJcsy4g.jpeg" /></figure><p>In my previous <a href="https://medium.com/@sakshamsingh5001/create-openapi-spec-from-postman-collection-using-node-js-718856d54327">article,</a> I showed you guys how you can convert your Postman collections into an OpenAPI specification. Today I will show you how you can generate cURL commands from your Postman collections and OpenAPI specifications.</p><h4>What is a cURL command?</h4><p>In very simple terms, a curl command is a way to make HTTP requests from the command line. Being able to make HTTP requests directly from the command line is convenient, especially for quick tests or automation tasks.</p><h4>What is a Postman collection?</h4><p>A Postman collection is a group of saved HTTP requests used in the Postman tool for API development. It helps us organise and manage requests, making it easier to test and share them with others. Collections store details like request URLs, headers, parameters, and scripts.</p><h4>What is an OpenAPI spec?</h4><p>Suppose you want to use an external API to fetch some data that will be used in your app. Two questions usually pop inside a developer’s head</p><p><em>How will I interact with the API?</em></p><p><em>Do I need their code to understand how to interact?</em></p><p>The answer to the second question is a big NO. One need not to understand a gigantic codebase to make certain API requests, all thanks to OpenAPI spec. One can interact with desired parts of the API to fulfil their requirements.</p><p>OpenAPI is a standardised approach to describe and document REST APIs.</p><p>Think of it as a blueprint or a contract that helps developers understand how to interact with an API without needing to dig into its code.</p><p>This standardisation makes it easier for developers to consume and integrate APIs into their applications, fostering better communication and interoperability between different software systems.</p><h4>Generate cURL commands using OpenAPI-Snippet library</h4><p>We’ll first load a Postman collection and convert it to an OpenAPI specification, which later will be used to get cURL commands.</p><p>We’ll use the following libraries to achieve our goal:</p><ol><li><em>Postman-to-OpenAPI</em></li><li><em>Js-Yaml</em></li><li><em>OpenAPI-Snippet</em></li></ol><p>Postman-to-OpenAPI helps us convert our Postman collection into an OpenAPI specification.</p><p>The Js-yaml library can parse YAML strings and convert them into JavaScript objects. This is useful when you have YAML data stored as strings and need to work with it in your JavaScript code.</p><p>The OpenAPI snippet will help us parse the YAML file and generate cURL commands using it.</p><p>Install libraries using the following commands:</p><pre>npm i postman-to-openapi<br>npm i openapi-snippet<br>npm i js-yaml</pre><p>Write the following code</p><pre>// Import the required libraries<br>  const postmanToOpenApi = require(&#39;postman-to-openapi&#39;)<br>  const OpenAPISnippet = require(&#39;openapi-snippet&#39;)<br>  const fs = require(&#39;fs&#39;);<br>  const yaml = require(&#39;js-yaml&#39;)<br><br>  const path=&#39;./your-postman-collection.json&#39; // Type the name of your input file<br>  const outputFile = &#39;./your-file-name.yml&#39;; // Type the name for your output OpenAPI spec<br>  const result = postmanToOpenApi(path, outputFile, { defaultTag: &#39;General&#39; })<br><br>  const target = [&#39;shell_curl&#39;];<br>  const openapi = yaml.load(fs.readFileSync(outputFile, &#39;utf8&#39;));<br>  const snippets = OpenAPISnippet.getSnippets(openapi, target);<br>  console.log(snippets)</pre><p>In case you want to generate cURL commands using your OpenAPI specification directly without using a Postman collection, you can skip the conversion of the Postman collection to an OpenAPI specification.</p><pre>// Import the required libraries<br>  const OpenAPISnippet = require(&#39;openapi-snippet&#39;)<br>  const fs = require(&#39;fs&#39;);<br>  const yaml = require(&#39;js-yaml&#39;)<br><br>  const target = [&#39;shell_curl&#39;];<br>  const inputFile = &#39;./your-file-name.yml&#39;<br>  const openapi = yaml.load(fs.readFileSync(inputFile, &#39;utf8&#39;));<br>  const snippets = OpenAPISnippet.getSnippets(openapi, target);<br>  console.log(snippets)</pre><p>Hope you found it helpful.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0341234172fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Javascript Unit Testing with Mocha and Chai]]></title>
            <link>https://singhsaksham.medium.com/introduction-to-javascript-unit-testing-with-mocha-and-chai-037d2a06bf3a?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/037d2a06bf3a</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mocha-js]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 09:03:05 GMT</pubDate>
            <atom:updated>2024-03-23T09:03:05.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*hjwK6ex4pHFrnACJ6_Bf6Q.png" /></figure><h4>What is Testing?</h4><p>In school, you study various subjects. To judge how well you have understood a subject, you give tests. Based on your performance in those tests, you are given a grade.</p><p>Similar to tests in school, to test how well the code you wrote is running, if it performs the intended task accurately, and to gauge how well it performs under different scenarios, we do testing.</p><h4>Unit Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*BAmFA_9PAuWTzHao.jpg" /><figcaption>Pic credits:<a href="https://programmerhumor.io/memes/unit-test/">https://programmerhumor.io/memes/unit-test/</a></figcaption></figure><p>A unit is the smallest block( or unit) of code in your app that can be independently executed. Unit testing is performing tests on that small unit of code, usually functions or methods, to ensure that they behave as expected in isolation from the rest of the app.</p><h4>Introduction to Mocha</h4><p>Mocha is a simple Javascript unit testing framework running on Node.js and in the browser. It helps us to create test suites and run unit tests on various parts of our code to check its robustness, efficiency, and functionality.</p><p>To install Mocha in your project, copy and paste the following command in your VS Code terminal or any other command line.</p><pre>npm i mocha</pre><p><strong>describe/it suites</strong></p><p>In Mocha <strong>describe()</strong> is a function which is used to define a test suite. A test suite is a collection of tests which are run on a unit( or block) of code. The describe function takes two parameters- name of the suite and a callback function which contains and executes various tests on the unit. The various tests are defined by the ‘it()’ function.</p><p>The <strong>it()</strong> function in Mocha is used to define an individual test case within a test suite. It takes two parameters: a string describing the test case and a callback function containing the actual test implementation</p><p>Below is an example of a basic test suite</p><pre>describe(&#39;Test_Suite_Name&#39;,function(){<br>    it(&#39;Functionality being tested&#39;,function(){<br>        //Add tests<br>        console.log(&quot;Test Success&quot;)<br>      })<br>})</pre><p>We’ll get back to this in while. Let’s now discuss Mocha Hooks</p><h4>Mocha Hooks</h4><p>In mocha, hooks help us to define preconditions before running tests and perform cleanup after the tests.</p><h4>before</h4><p>The <strong>before() </strong>hook runs once before any test cases in the current describe block run.</p><pre>describe(&#39;Before hook&#39;, function () {<br>  before(&#39;Title&#39;,function () {<br>    // runs once before the first test in this block<br>  });<br>});</pre><h4>before each</h4><p>The <strong>beforeEach()</strong> hook runs before every test case in the describe block.</p><pre>describe(&#39;BeforeEach hook&#39;,function(){<br>  beforeEach(&#39;Title&#39;,function () {<br>    // runs before each test in this block<br>  });<br>})</pre><h4>after</h4><p>The <strong>after()</strong> hook runs after all test cases in the describe block have finished executing</p><pre>describe(&#39;After hook&#39;,function(){<br>  after(&#39;Title&#39;,function () {<br>    // runs after all tests have executed<br>  });<br>})</pre><h4>after each</h4><p>The <strong>afterEach()</strong> hook runs after every test case in the describe block.</p><pre>describe(&#39;AfterEach hook&#39;,function(){<br>  afterEach(&#39;Title&#39;,function () {<br>    // runs after each test in this block<br>  });<br>})</pre><h4>Chai</h4><p>It is an assertion library for Javascript(often used with Mocha) used to make assertions for your code. Suppose you make an API request and you are expecting a boolean value in response. You can make an assertion to expect boolean values in response and if you receive some other data type then the assertion will fail, providing valuable feedback on the correctness of the code.</p><p>To install Chai in your project run the following command</p><pre>npm i chai</pre><p>Now let us modify the describe/it suite we saw earlier in the article.</p><pre>const {assert} =require(&#39;chai&#39;)<br><br>describe(&#39;Test_Suite_Name&#39;,function(){<br>    it(&#39;Functionality being tested&#39;,function(){<br>        //Add tests<br>        let a=2;<br>        let b=5;<br>        assert.equal(a+b,8);<br>        console.log(&quot;Test Success&quot;)<br>      })<br>})</pre><p>Here we have defined an assertion that the sum of two variables ‘a’ and ‘b’ should be equal to 8. If it is equal then the assertion is valid and the test case passes else it fails.</p><p>We can use assertions to check parts of our code and see if they are giving us the desired output or not.</p><p>That’s all for today.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=037d2a06bf3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create OpenAPI spec from Postman Collection using Node.js]]></title>
            <link>https://singhsaksham.medium.com/create-openapi-spec-from-postman-collection-using-node-js-718856d54327?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/718856d54327</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 08:32:39 GMT</pubDate>
            <atom:updated>2024-03-16T08:32:39.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plYHdia1CBMYvZVHcoA8Ig.jpeg" /></figure><p>I recently worked on a project that involved converting a Postman collection in JSON to an OpenAPI specification(spec) using Node.js. While there are many online tools available for this task, have you ever wondered how you could build a similar tool yourself?</p><p>Before diving into that, let’s briefly discuss what an OpenAPI spec is.</p><h4>What is OpenAPI?</h4><p>Suppose you want to use an external API to fetch some data that will be used in your app. Two questions usually pop inside a developer’s head</p><p><em>How will I interact with the API?</em></p><p><em>Do I need their code to understand how to interact?</em></p><p>The answer to the second question is a big NO. One need not to understand a gigantic codebase to make certain API requests, all thanks to OpenAPI spec. One can interact with desired parts of the API to fulfil their requirements.</p><p>OpenAPI is a standardised approach to describe and document REST APIs.</p><p>Think of it as a blueprint or a contract that helps developers understand how to interact with an API without needing to dig into its code.</p><p>This standardisation makes it easier for developers to consume and integrate APIs into their applications, fostering better communication and interoperability between different software systems.</p><h4>Postman-to-OpenAPI Library</h4><p>Postman-to-OpenAPI library can be used to convert postman collections to OpenAPI specs. Simply visit the link below and install the library into your project using npm</p><p><a href="https://www.npmjs.com/package/postman-to-openapi">https://www.npmjs.com/package/postman-to-openapi</a></p><pre>npm i postman-to-openapi</pre><p>Using yarn</p><pre>yarn add postman-to-openapi</pre><h4>Code</h4><pre>const postmanToOpenApi = require(&#39;postman-to-openapi&#39;)<br><br><br>async function main(){<br> //Specify path to your postman collection<br> const postmanCollectionPath = &#39;./path/to/postman/collection.json&#39;<br><br> const outputFilePath = &#39;./spec.yml&#39;<br>    try {<br>    const result = await postmanToOpenApi(postmanCollectionPath, outputFilePath, { defaultTag: &#39;General&#39; })   <br>    console.log(`OpenAPI spec ${result}`)<br>  } <br>   catch (err) {<br>    console.log(err)<br> }<br>  <br>}</pre><p>In the provided code snippet, we begin by importing the library using ES5 syntax, storing it in the constant ‘postmanToOpenApi’. Within the main function, two additional constants are required: one specifying the path to your Postman collection, and the other specifying the path where you want the output OpenAPI spec to be generated.</p><p>If you don’t want to save the output you can make the ‘outputFilePath’ as null.</p><p>You can now use the generated OpenAPI spec in your application according to your specific requirements.</p><p>To know more about this library you can read the docs <a href="https://joolfe.github.io/postman-to-openapi/">here</a>.</p><p>Hope you found it helpful.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=718856d54327" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Learn Kubernetes from Scratch]]></title>
            <link>https://blog.devops.dev/lets-learn-kubernetes-from-scratch-f4f800668da2?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f800668da2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 17:59:06 GMT</pubDate>
            <atom:updated>2024-02-20T18:02:56.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OKZ9hj4pMAJ2mZ_-" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous article I wrote about Docker. It will be a pre-requisite for Kubernetes. If you are already familiar with Docker then read ahead, otherwise you should learn Docker first either from my article given below or from anywhere you like.</p><p>You can find the article <a href="https://blog.devops.dev/lets-learn-docker-from-scratch-in-2023-d831629c5497"><strong>here</strong></a><strong>.</strong></p><p>Done with Docker? Great, let’s get started with Kubernetes</p><p>Today we’ll dive into another important tool called Kubernetes(k8s in short). We’ll start from the very basic and build a strong foundation. This will be a long one so bear for a while.</p><h4>Overview</h4><p>We’ll be covering</p><ol><li>Revisiting Containers and Images</li><li>Container Orchestration</li><li>What is Kubernetes?</li><li>Why Kubernetes?</li><li>Kubernetes Architecture</li><li>Kubernetes Components</li></ol><p>Let’s revise containers once again</p><h3>Containers and Images</h3><p>An image is a template used to defining containers.It is like a blueprint of the environment required to run an application. Containers are the actual running instance of the image.</p><p>It is analogous to how classes and objects are defined in Object Oriented Programming. Classes define the blueprint for an object. Object is an instantiation of the class.</p><h3>Container Orchestration</h3><p>Imagine you’re building a web application, starting with just two containers — one for the frontend and one for the backend — suitable for handling low loads. However, as your web app gains popularity and the user base expands, manual management of containers becomes impractical. This is where container orchestration steps in.</p><p>Container orchestration is the key to efficiently managing, deploying, and scaling your containerized applications in dynamic and demanding environments. It automates decisions on how many containers to run or stop based on factors like increased demand, ensuring that your application seamlessly scales to meet user requirements.</p><p>This automated approach to operations, combined with features like load balancing, resource optimization, and rolling updates, simplifies the complexities of managing a growing and evolving web application, making it easier to maintain efficiency and reliability at scale.</p><h3>What is Kubernetes(K8s)?</h3><p>Kubernetes, often abbreviated as K8s, is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. It was originally developed by Google and is now maintained by the Cloud Native Computing Foundation (CNCF).</p><h3>Why Kubernetes?</h3><p>Kubernetes simplifies containerized application management through automation, ensuring portability, dynamic scaling, efficient resource usage, and seamless networking.</p><p>Its features include:</p><p>1. Declarative configuration<br>2. Strong community support<br>3. Focus on cloud-native principles<br>4. Leading choice for modern, scalable deployments<br>5. Self-healing capabilities</p><h3>Kubernetes Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TT7kDSSqzbiGAWu5H3kcPA.png" /></figure><h3>Kubernetes Components</h3><p>Kubernetes has plenty of components all of which I can’t cover but here are some of the most basic and used components which will help you get started.</p><h3>Cluster</h3><p>A Kubernetes cluster is a group of resources for deploying, managing, and scaling containerized applications. It simplifies development and management with features like automatic scaling, updates, service discovery, and load balancing.</p><h3>Control Plane</h3><p>The control plane consists of the master node components (API server, controller manager, scheduler) responsible for maintaining the desired state of the cluster. It makes decisions about when and where to run pods, ensuring the overall health and functionality of the Kubernetes cluster.</p><h3>Master node</h3><p>The master node is the control plane component responsible for managing the overall state of the cluster. It includes the API server, controller manager, scheduler, and etcd. The master node coordinates and manages the worker nodes. Here’s a brief about each component of the master node:</p><h4>1. API Server</h4><p>The API server in Kubernetes is the central management point for the cluster. It handles interactions from users, administrators, and Kubernetes components, enforcing security, validating requests, and maintaining the cluster’s state. Through the API server, users can deploy applications, configure resources, and monitor cluster health.</p><p>Users and administrators interact with the API server using tools like kubectl.</p><h4>2. Controller Manager</h4><p>The controller manager in Kubernetes is like the brain behind the orchestration. It’s responsible for monitoring the health of nodes in the cluster and taking action based on their status. For example, if a node stops responding, the controller manager can initiate actions like rescheduling workloads to other healthy nodes.</p><h4>3. Scheduler</h4><p>etcd is a distributed key-value store used by Kubernetes to store and manage configuration data, state information, and metadata. It serves as the cluster’s reliable source of truth, ensuring consistency across the entire system.</p><h4>4. etcd</h4><p>The Scheduler in Kubernetes is responsible for assigning work (containers) to nodes in the cluster. It considers factors like resource requirements, node capacity, and constraints to optimize the allocation of workloads.</p><h3>Worker node</h3><p>Worker nodes, also known as minion nodes, are responsible for running containers. They receive instructions from the control plane and manage the runtime environment for containers.</p><p>As a developer or Kubernetes administrator, your primary focus will often revolve around worker nodes. Whether you’re deploying containerized applications, autoscaling, or implementing updates, working with worker nodes is a consistent aspect of managing production-grade servers.</p><h4>Kube-proxy</h4><p>Kube-proxy is a network proxy that runs on each node in a Kubernetes cluster. Its primary function is to manage network connectivity to services running inside the cluster.</p><h4>Pods</h4><p>Pods are the smallest deployable units in Kubernetes. They represent a single instance of a running process and can contain one or more tightly coupled containers. Pods share the same network namespace, allowing them to communicate with each other more easily.</p><h3>Kubelet</h3><p>A kubelet is responsible for managing individual nodes. It runs on each node and ensures that containers are running in a Pod as expected. It keeps an eye on their health, manages their resources like memory and CPU, and makes sure they have what they need to work properly.</p><h3>High-level Kubernetes Objects</h3><h4>1. replicasets</h4><p>ReplicaSets ensure a specified number of identical pod replicas are running at all times. If a pod fails or needs to be scaled, the ReplicaSet controller automatically adjusts the number of replicas to maintain the desired state.</p><h4>2. Ingress</h4><p>Ingress is an API object that manages external access to services within a cluster. It allows the definition of rules for routing external HTTP and HTTPS traffic to services based on hostnames or paths.</p><h4>3. Service</h4><p>Services define a set of pods and provide a stable endpoint for accessing them. They enable load balancing and service discovery within the Kubernetes cluster, allowing communication between different parts of an application.</p><h4>4. Configmap</h4><p>ConfigMaps store configuration data in key-value pairs, separate from application code. They provide a way to decouple configuration from containers, making it easier to manage and update configurations independently.</p><h4>5. Secret</h4><p>Secrets store sensitive information, such as passwords or API keys, in a more secure way than ConfigMaps. They are base64 encoded and are intended to be used for storing confidential data.</p><p>I’ll talk about YAML files in my next article. YAML files are used to define and configure containerised applications and their environments. They provide a human-readable and easily editable format for describing complex application architectures.</p><p>That’s all for today. Kubernetes is huge but all the content above will definitely help you get started.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f800668da2" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/lets-learn-kubernetes-from-scratch-f4f800668da2">Let’s Learn Kubernetes from Scratch</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxies Explained]]></title>
            <link>https://singhsaksham.medium.com/proxies-explained-5d098aa8d7d7?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d098aa8d7d7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 07:29:17 GMT</pubDate>
            <atom:updated>2024-02-17T07:29:17.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SwuLUaaAuQ5CLEAg" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Proxies are an essential component of any modern day application.Proxies act as an intermediary between server and client.</p><p>But why add a proxy server between a server and client?</p><p><strong>1) Improves security : </strong>Proxies make things safer online. They stop harmful stuff like viruses, block dangerous websites, and follow security rules. They also hide your internet address, which helps keep you safe from being tracked or targeted by attackers.</p><p><strong>2) Data Caching : </strong>Proxies speed up access to frequently requested content by storing copies locally, reducing the need for repeated requests to the original source and easing network load</p><p><strong>3) Load Balancing: </strong>Many web apps receive multiple requests on a daily basis. If there is a single server to cater all requests, the server can get overloaded and crash. To prevent such scenarios we can use a load balancer to distribute incoming requests evenly among multiple servers. A reverse proxy server can act as a load balancer and thus help in managing large number of requests.</p><p><strong>4) Anonymity : </strong>Proxies help hide the IP addresses of both client and server. Thus neither the server can know which user send this request nor the client can know which server gave the response. There’s a certain degree of anonymity provided to both client and server.</p><p><strong>5) Data Filtering : </strong>Proxies help filter data by controlling what users can access, blocking harmful content, and scanning for malware. Many organizations deploy firewalls to fulfill this objective as part of their network security measures</p><p>I’ll be talking about forward and reverse proxies although there are more types.</p><h3>Forward Proxy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jVh5hpERMQ7cRH9h" /></figure><p>In forward proxy, the proxy sits on the client side and forwards the client’s requests to the targeted backend server.</p><p>The client’s IP address is also protected and cannot be known by the server.</p><p>A good example is a VPN( Virtual Private Network). Suppose you work for an organisation that restricts your access to some websites, say YouTube.</p><p>Here’s how it works: You connect to the VPN service, which then acts as a forward proxy on your behalf. When you access YouTube through the VPN, your requests are routed through the VPN server. From YouTube’s perspective, it appears as though the requests are coming from the IP address of the VPN server, not your actual IP address. This not only allows you to access restricted content but also ensures that your browsing activity remains private and anonymous.</p><p>In addition to providing access to restricted content, forward proxies like VPNs offer other benefits such as encrypting your internet traffic to protect it from eavesdropping or interception. This encryption helps safeguard your sensitive information, such as login credentials or personal data, especially when using unsecured public Wi-Fi networks.</p><h3>Reverse Proxy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yinphgzOof9I0oYs" /></figure><p>Reverse proxies, on the other hand, are setup on the server side. They redirect the incoming requests from various clients to appropriate servers. Similar to forward proxies, with reverse proxies, the server’s IP address gets hidden from the client.</p><p>Reverse proxies help with load balancing, data caching, security,etc. Reverse proxies also provide a single point of access for clients, simplifying network architecture and enhancing scalability. Nginx is a popular tool used as a reverse proxy. It emerges as a preferred solution for implementing reverse proxy functionality, empowering organizations to optimize their web traffic management effectively.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d098aa8d7d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Learn Docker from Scratch in 2023]]></title>
            <link>https://blog.devops.dev/lets-learn-docker-from-scratch-in-2023-d831629c5497?source=rss-db3721ffe2c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d831629c5497</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Saksham Singh]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 07:27:51 GMT</pubDate>
            <atom:updated>2023-10-12T18:42:54.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*mLmRmAt0MQFaiLTdO0Mokw.png" /></figure><p>Docker is a software platform that allows developers to package and run their applications in isolated environments called “containers”. Docker simplifies the process of building, deploying, and scaling applications by providing a consistent runtime environment, enabling developers to focus on writing code rather than managing infrastructure.</p><p>Not to worry if you don’t seem to understand the above definition right now. By the end of this article, we will understand all the basic concepts related to docker and build a strong foundation.</p><p>Before we start learning about docker, let’s first try to understand why we need it in the first place.</p><h3>Before Docker</h3><p>Say you are building a web application using React and Node.js . Let’s say you used a certain version of both React and Node to create this application. It’s a really nice app and you ask your friend to try it on his machine.</p><p>But your friend tells you that your web app did not work on his machine. This is the typical “but it works on my machine” problem. There can be multiple reasons why your app did not work on his machine but for now it is the version mismatch of React and Node.js which caused this problem.</p><p>Now imagine if you were to build this application for a large number of users or a client. How to ensure the application you built is running on each device despite having different versions of various dependencies or other configurations.</p><p>To ensure consistency and reliability, developers earlier resorted to virtual machines and provisioning tools like VirtualBox, VMware, and Vagrant. These tools allowed them to create isolated environments that closely mirrored their development setup. However, managing these virtual machines could be cumbersome, and they were often resource-intensive.</p><h3>Why Docker?</h3><p>With Docker, you can encapsulate your React and Node.js application, along with the specific versions of React, Node.js, and any other dependencies, into a Docker container. This container could be shared with your friend or deployed on a client’s machine without worrying about version mismatches or compatibility issues. Docker ensured that the application ran in the same way, with the same environment, on any system that supported Docker.</p><p>Docker has made it easier to manage and orchestrate containers at scale. Tools like Docker Compose and Kubernetes allowed developers to define complex multi-container applications and manage them seamlessly in production environments.</p><p>We’ll talk more about these tools in the future. Now let’s get hands on demo with docker</p><h3>Containers and Images</h3><p>An image is a template used to defining containers.It is like a blueprint of the environment required to run an application. Containers are the actual running instance of the image.</p><p>It is analogous to how classes and objects are defined in Object Oriented Programming. Classes define the blueprint for an object. Object is an instantiation of the class.</p><h3>Docker Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYta19zs3RmPlWz964cFcw.png" /><figcaption>Source: <a href="https://docs.docker.com/get-started/images/docker-architecture.png">https://docs.docker.com/get-started/images/docker-architecture.png</a></figcaption></figure><p>Docker uses a client-server architecture. The interaction in Docker involves the Docker client and the Docker daemon. The Docker client is responsible for initiating actions like building, running, and sharing Docker containers, while the Docker daemon handles the heavy lifting of executing these tasks. Both the Docker client and daemon can coexist on the same machine, or you can set up a Docker client to connect to a remote Docker daemon. They communicate through a REST API, which operates either via UNIX sockets or a network interface.</p><h4>Docker Client</h4><p>This is where a Docker user writes the commands to interact with the docker daemon via the API.</p><h4>Docker Daemon</h4><p>The Docker daemon, referred to as “dockerd,” is responsible for receiving Docker API requests and overseeing various Docker entities, including images, containers, networks, and volumes.</p><h4>Docker Registries</h4><p>A Docker registry, like Docker Hub, stores Docker images. When you use “docker pull” or “docker run,” Docker fetches images from your registry configuration. For “docker push,” Docker sends your image to your configured registry.</p><h3>Installation</h3><p>You can go to the official Docker documentation for this and download docker desktop according to your OS: <a href="https://docs.docker.com/desktop/install/mac-install/">https://docs.docker.com/desktop/install/mac-install/</a></p><h3>Docker Commands</h3><p>Though there are a bunch of different commands we’ll be looking at some of the most used commands helping you get started with docker:</p><h4>docker ps</h4><p>This command lists running containers, displaying their IDs, names, status, and other information.</p><p>Syntax</p><pre>docker ps</pre><h4>docker version</h4><p>This command shows information about the Docker client and server versions.</p><p>Syntax</p><pre>docker version</pre><p>It shows information about the Docker client and server versions.</p><h4>docker start</h4><p>It starts a stopped container.</p><p>Syntax</p><pre>docker start [container]</pre><h4>docker stop</h4><p>It stops a running container</p><p>Syntax</p><pre>docker stop [container]</pre><h4>docker images</h4><p>It lists all available Docker images on your system.</p><p>Syntax</p><pre>docker images</pre><h4>docker pull</h4><p>It downloads a Docker image from a registry (e.g., Docker Hub) to your local system.</p><p>Syntax</p><pre>docker pull [image]</pre><h4>docker rm</h4><p>It removes one or more stopped containers from your system.</p><p>Syntax</p><pre>docker rm [container]</pre><h4>docker rmi</h4><p>It deletes one or more Docker images from your system.</p><p>Syntax</p><pre>docker rmi [image]</pre><h4>docker kill</h4><p>It stops a running container forcefully</p><p>Syntax</p><pre>docker kill [container]</pre><h4>docker push</h4><p>This command pushes a Docker image to a container registry, making it available for others to download</p><p>Syntax</p><pre>docker push [image]</pre><h4>docker run</h4><p>It creates and starts a new container from a specified image with specified options, commands, and arguments.</p><p>Syntax</p><pre>docker run [options] [image] [command] [args]</pre><h4>docker COMMAND — — help</h4><p>You can find out more about what a command does using this command.Just mention which command you want to know about</p><p>Syntax</p><pre>docker [command] --help</pre><p>That’s all for today. There are many more commands you can use while working with docker, but the above ones are the basic and most commonly used ones and will help you get started.</p><p>Any suggestions are highly welcome, thank you for reading.</p><p>Feel free to connect with me on other platforms: <a href="https://www.linkedin.com/in/sakshamsingh5001/">LinkedIn</a> <a href="https://github.com/Saksham294">GitHub</a> <a href="https://twitter.com/sakshams294">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d831629c5497" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/lets-learn-docker-from-scratch-in-2023-d831629c5497">Let’s Learn Docker from Scratch in 2023</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>