<?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 Endurance, the Martian on Medium]]></title>
        <description><![CDATA[Stories by Endurance, the Martian on Medium]]></description>
        <link>https://medium.com/@hendurhance?source=rss-ea43bc51c3f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3GcvwoNkjeEk4LjgNEfY3g.png</url>
            <title>Stories by Endurance, the Martian on Medium</title>
            <link>https://medium.com/@hendurhance?source=rss-ea43bc51c3f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:57:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hendurhance/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[The Missing Penny Problem, and the 1792 Voting Rule That Fixes It]]></title>
            <link>https://blog.devgenius.io/the-missing-penny-problem-and-the-1792-voting-rule-that-fixes-it-e1e2fa443c50?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1e2fa443c50</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 21:06:01 GMT</pubDate>
            <atom:updated>2026-08-17T21:06:01.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XPVoVxO4hRgGqwVJ" /><figcaption>Photo by <a href="https://unsplash.com/@ryanquintal?utm_source=medium&amp;utm_medium=referral">Ryan Quintal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I was arguing with a friend recently about where we learned the Hamilton method. He swore it was third-year Operations Research, and I was convinced it was Numerical Analysis. We went back and forth for a while, digging up memories of lectures we mostly slept through. It felt like pointless trivia until I needed it to fix a bug.</p><p>The bug was in how we applied discounts. When you take a fixed discount at the order level and spread it across several line items, simple division no longer works. Split a $0.10 discount across three items and each one is owed $0.0333…, which rounds to $0.03. Three items at $0.03 comes to $0.09.</p><p>A penny vanishes.</p><p>In software, disappearing money makes accountants nervous, and it makes reconciliation fail. You also can’t hand the spare penny to the first line item and move on, because the first line item is always the same one. Over a few thousand orders, whichever product sits at the top of the cart quietly accumulates a discount the others never get, and your per-product margin report starts lying to you. What you need is a rule that decides who gets the spare penny, returns the same answer every time it runs, and always adds back up to the amount you started with.</p><p>Alexander Hamilton wrote that rule in 1792, for splitting seats in the US House of Representatives among the states. George Washington vetoed the bill that carried it, which was the first presidential veto in American history, and Congress didn’t adopt the method until 1852. Most people call it the largest remainder method now. It works just as well on pennies as it did on congressmen.</p><h4>The pizza version</h4><p>Three friends order 8 slices of pizza and split the bill unevenly. Alice puts in $6.50, Bob puts in $9.50, and Charlie puts in $4.00, so the bill comes to $20. Each person’s exact share of the pizza is whatever fraction of the bill they paid:</p><p>- Alice: $6.50 / $20 × 8 = <strong>2.6 slices</strong><br>- Bob: $9.50 / $20 × 8 = <strong>3.8 slices</strong><br>- Charlie: $4.00 / $20 × 8 = <strong>1.6 slices</strong></p><p>Nobody wants 0.6 of a slice, so every share has to become a whole number, and all 8 slices still have to be handed out.</p><p><strong>Step 1 — give everyone their whole slices.</strong> Alice takes 2, Bob takes 3, Charlie takes 1. That accounts for 6 slices and leaves 2 on the table.</p><p><strong>Step 2 — write down what each person is still owed.</strong> Alice 0.6, Bob 0.8, Charlie 0.6.</p><p><strong>Step 3 — give the spare slices to the largest leftovers, in order</strong>. Bob’s 0.8 is the largest, so he takes one. Alice and Charlie are tied on 0.6, so you need a tie-break rule that returns the same answer on every run. Take whichever one comes first in the list, and Alice gets the last slice.</p><p>Alice finishes on 3, Bob on 4, Charlie on 1. Every share is a whole number, and all 8 slices are gone.</p><p>Swap slices for cents and that is the entire method.</p><p>The version I wrote first</p><pre>import math<br><br>def distribute_amount(total_amount, weights):<br>    total_weight = sum(weights)<br><br>    # 1. What each item is owed, exactly<br>    exact_shares = [(w / total_weight) * total_amount for w in weights]<br><br>    # 2. Give everyone their whole units<br>    allocated = [math.floor(s) for s in exact_shares]<br><br>    # 3. What&#39;s left over for each item<br>    remainders = [s - a for s, a in zip(exact_shares, allocated)]<br><br>    # 4. Hand the spare units to the largest remainders<br>    units_left = total_amount - sum(allocated)<br>    sorted_indices = sorted(<br>        range(len(remainders)),<br>        key=lambda i: remainders[i],<br>        reverse=True<br>    )<br>    for i in range(int(units_left)):<br>        allocated[sorted_indices[i]] += 1<br><br>    return allocated<br><br><br># 10 cents across three equal items<br>print(distribute_amount(10, [1, 1, 1]))   # [4, 3, 3]</pre><p>That code is correct on both examples in this article. It returns <em>[4, 3, 3]</em> for the ten-cent case, and it returns Alice 3, Bob 4, Charlie 1 for the pizza. It also carries the same class of bug it was written to fix.</p><p>The remainders are floats. Two line items can be owed remainders that are exactly equal as fractions and still compare as different numbers once they have been through a division. I ran this version against an integer implementation on 200,000 random allocations to check that they agreed, and they disagreed on one:</p><pre>total = 940194<br>weights = [778344, 212360, 105113, 190393, 4674, 386802, 486499]<br>integer version → [338139, 92256, 45665, 82713, 2030, 168040, 211351]<br>float version → [338138, 92256, 45665, 82713, 2031, 168040, 211351]</pre><p>The first and fifth items are owed exactly the same remainder, 1171206/2164185. In floating point they arrive as two different numbers:</p><pre>item 0 → 0.5411764705786481<br>item 4 → 0.5411764705881978</pre><p>The first item’s share is much larger, so more of its bits go to the integer part and fewer are left for the fraction. It loses a tie that the tie-break rule says it should win. Both versions still hand out all 940,194 units, so no money goes missing. They just disagree about which line item receives the spare one, and they disagree for a reason nobody can see by reading the code or explain to an auditor.</p><h4>Doing it with integers</h4><p>The fix is to stay in whole units and never divide. In Python, `//` gives you the whole units an item is owed and `%` gives you the exact remainder as an integer, so the sort compares two integers and there is nothing left to round.</p><pre>def distribute(total, weights):<br>    &quot;&quot;&quot;Split `total`, in minor units, across `weights`.<br><br>    Always returns integers that sum to exactly `total`.<br>    &quot;&quot;&quot;<br>    total_weight = sum(weights)<br><br>    # Whole units owed outright, and the exact leftover, both as integers<br>    base      = [(w * total) // total_weight for w in weights]<br>    remainder = [(w * total) %  total_weight for w in weights]<br><br>    # Spare units go to the largest remainders. Ties go to the earlier<br>    # item, which keeps the result identical on every run.<br>    spare = total - sum(base)<br>    order = sorted(range(len(weights)), key=lambda i: (-remainder[i], i))<br>    for i in order[:spare]:<br>        base[i] += 1<br><br>    return base<br><br><br>distribute(10, [1, 1, 1])        # [4, 3, 3]  — 10 cents, three items<br>distribute(8, [650, 950, 400])   # [3, 4, 1]  — the pizza</pre><p>One rule comes with it: pass the amount in minor units. Cents, kobo, satoshi, whatever the smallest indivisible unit of your currency is. Hand the float version <strong>0.10</strong> instead of <strong>10</strong> and it returns <strong>[0,0,0]</strong> without complaining, because <strong>math.floor(0.0333)</strong> is 0 for every item and <strong>int(0.10)</strong> is 0, so the loop that distributes the remainder never runs at all. The discount disappears completely, which is a worse outcome than the penny you started out trying to save.</p><p>We put the integer version into the sales reports. The rounding errors stopped, and <strong>product_total</strong> finally matched <strong>order_total</strong>.</p><p>I still think I learned this in Numerical Analysis, and my friend still refuses to concede. Neither of us remembered that the method comes with a warning about how you implement it, and that is probably the part they covered while we were asleep.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1e2fa443c50" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/the-missing-penny-problem-and-the-1792-voting-rule-that-fixes-it-e1e2fa443c50">The Missing Penny Problem, and the 1792 Voting Rule That Fixes It</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Websocket vs. Webhook: Determining the Perfect Fit for Your Next Project]]></title>
            <link>https://blog.devgenius.io/websocket-vs-webhook-determining-the-perfect-fit-for-your-next-project-2cf7b01c43a1?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf7b01c43a1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 13:20:39 GMT</pubDate>
            <atom:updated>2025-10-27T13:22:34.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNnsSOYXzbti0rdXoCIf5g.png" /><figcaption>Photo by <a href="https://budibase.com/">BudiBase</a></figcaption></figure><p>Have you ever ordered something online and received updates on your package every step of the way, right from the warehouse, through every city checkpoint, until it finally lands at your doorstep? Or perhaps you’ve been glued to your screen during a crazy football match, watching live updates flash instantly across the screen. Behind these notifications that seem to happen are two important technologies quietly powering our apps: <strong>Websockets</strong> and <strong>Webhooks</strong>. If you’ve heard this before or you haven’t, let me reassure you: despite their intimidating names, they’re simpler than you think.</p><p>Let’s break it down slowly. By the time we’re done, you’ll know exactly when to use each one, even if you don’t write a single line of code yourself.</p><h3>First Up: Websockets The Real-Time Chatters</h3><p>Imagine you’re chatting with your best friend over WhatsApp. You send a meme; seconds later, they reply with an emoji. That rapid back-and-forth exchange is Websockets in action. They set up a live, continuous two-way conversation between an app and a server. Think of Websockets as having an open phone line that is always connected, ready to reply to you instantly.</p><p>This makes them ideal for apps that rely heavily on instant interactions. Examples?</p><ul><li><strong>Messaging apps</strong> like WhatsApp or Telegram, where instant conversation matters.</li><li><strong>Live sports apps</strong> showing scores the moment a goal hits the net, or when the ball or someone scores, is called a two-pointer</li><li><strong>Uber or Lyft</strong>, where you watch your ride inch closer in real-time to the location you requested.</li></ul><p>However, this real-time conversation comes at a cost. Maintaining an always on connection consumes a lot of resources like battery and bandwidth, it’s a bit like leaving a video call open all day, which in turn drains your device battery and internet data. Plus, it requires more infrastructure to manage, which might be a bit excessive for simpler tasks.</p><h3>On the Other Hand: Webhooks The Polite Messenger</h3><p>Ever signed up for a newsletter on your favorite brand website, received a welcome email immediately, and another email only when something interesting happens, like a sale that is coming up or a special event? That’s exactly how Webhooks operate. Instead of keeping a constant open line, Webhooks politely wait until something noteworthy happens (or, as I like to call it, when an event occurs). When it does, they send out a quick notification to inform other apps or services, kind of like tapping you on the shoulder to say, “Hey, something cool just happened!”</p><p>Here’s where Webhooks shine:</p><ul><li><strong>Payment notifications</strong>: You purchase something, and your bank instantly pings you with a confirmation text. No need to continuously check the bank’s app; they’ll let you know.</li><li><strong>Email alerts</strong>: Like receiving immediate confirmation emails when you book a flight or hotel.</li><li><strong>Social media updates</strong>: Instagram sends you notifications whenever someone likes your post or story.</li></ul><p>The beauty of Webhooks mainly lies in how simple and efficient they are. Because they only “come on” when necessary, they’re lighter on resources. But they aren’t perfect; there might be slight delays. They’re fast, but not always instantaneous like Websockets. Think of it as sending a quick email instead of having an ongoing conversation; there might be a tiny wait before the message arrives.</p><h3>Let’s See These in Action: A Quick Example (No Tech Jargon, Promise!)</h3><p>Let’s say you run a popular online store selling limited-edition sneakers (maybe, you’re a sneakerhead 😏). Your customers eagerly await restocks.</p><p>If you pick <strong>Websockets</strong>, Customers stay glued to your app, watching sneakers restock instantly. Great if your users are hardcore fans who absolutely must know the exact second new sneakers hit the shelves. But beware, it demands more resources, potentially draining battery and bandwidth, and requiring stronger servers.</p><p>If you go with <strong>Webhooks, </strong>Users simply receive a push notification or email the moment sneakers drop. Most people love this; it’s efficient, less resource-intensive, and perfect for casual fans who don’t need to stare at their screens constantly.</p><p>See the difference? Each technology has its sweet spot. Your choice depends entirely on your users’ behavior, preferences, and how much infrastructure you’re willing to manage behind the scenes.</p><h3>Pros, Cons, and Everything in Between</h3><p>When thinking about <strong>Websockets</strong>, consider this: they deliver updates at lightning-fast speed, which might feel magical, but require ongoing resources to keep that magic alive. This makes them perfect for apps needing constant interaction (think gaming, messaging, or real-time tracking apps). The downside? They can be heavier and more complex to maintain.</p><p><strong>Webhooks</strong>, meanwhile, are super efficient and friendly on your resources. They politely notify only when something important happens, no constant connection needed. They’re great for simpler, less frequent updates (like emails or notifications). Their only catch? Slightly less instant, though typically fast enough that most users won’t notice.</p><h3>Which One is Actually Better?</h3><p>Ah, finally, the million-dollar question! But the answer isn’t about which is better overall, it’s about what’s better for your specific scenario.</p><p>Ask yourself:</p><ul><li>Do my users need instant, constant updates? → <strong>Websocket</strong></li><li>Can they wait a second or two without stress? → <strong>Webhook</strong></li><li>Do I have the resources to support always-on connections? → <strong>Websocket</strong></li><li>Or am I looking for simpler, efficient notifications? → <strong>Webhook</strong></li></ul><h3>Conclusion</h3><p>Whether you’re a project manager, business owner, or just curious about the tech, understanding Websockets vs. Webhooks isn’t as scary as it first seems. It’s all about deciding how quickly your users need information and how much behind-the-scenes complexity you’re willing to handle.</p><p>My advice? Think about your favorite apps and notice how each communicates with you. Once you spot the patterns, choosing between Websockets and Webhooks will be so much easier. And if you’re still stuck? Remember, you don’t need to be a 10x engineer to make smart tech decisions. Just make sure you consider your user in every decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf7b01c43a1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/websocket-vs-webhook-determining-the-perfect-fit-for-your-next-project-2cf7b01c43a1">Websocket vs. Webhook: Determining the Perfect Fit for Your Next Project</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Jest into Your Node.js API Development for Better Test Coverage]]></title>
            <link>https://blog.devgenius.io/how-to-integrate-jest-into-your-node-js-api-development-for-better-test-coverage-6b878738a833?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b878738a833</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 09:32:52 GMT</pubDate>
            <atom:updated>2024-04-15T16:29:07.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MC7LODHTS460Zlal" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever tried to find your phone when it’s in silent mode? If you’re anything like me (and our dear Gen Z brethren), the ‘Do Not Disturb’ setting is practically our best friend. You know the drill: retracing your steps, checking the usual suspects — the couch cushions, the gap between armchairs, the kitchen counter. It turns into a little game of hot and cold, right? And if you are lucky, you stumble on it before the day ends. This, my friends, is a perfect analogy for testing an API without the proper tools in place. It turns into a never-ending search to spot those tricky bugs or issues. You need a systematic approach to find what’s out of place, what’s missing, and what needs a little tweak to keep everything running smoothly.</p><p>Now, imagine if you had a device that could lead you straight to your silent phone, cutting through the guesswork (like Airtags). That’s Jest for your API. It’s like your personal API detective, magnifying glass in hand, ready to inspect every piece of your code. In this article, we will discuss how to integrate Jest to test our Node.js API.</p><h3>Setting Up Your Node.js Project</h3><p>First things first, let’s get our development environment set up. You’ll need Node.js and npm (or yarn) installed on your machine. If you haven’t already, hop on over to the Node.js website and download the latest version using the instructions below:</p><h3>Node.js Installation:</h3><p>Head over to the Node.js website (<a href="https://nodejs.org/">https://nodejs.org/</a>) and download the latest version of Node.js for your operating system. The website should automatically detect which version you need, but if not, just choose the appropriate one for your setup.</p><p>Once the download is complete, run the installer and follow the on-screen instructions. It’s a pretty straightforward process — just click ‘Next’ a bunch of times and you’ll be good to go.</p><h3>npm/yarn Installation:</h3><p>npm (Node Package Manager) comes bundled with Node.js, so once you’ve installed Node.js, you’ll have npm ready to roll. If you prefer yarn, you can install it using npm by running the following command in your terminal:</p><pre>npm install -g yarn</pre><h3>Initializing a Node.js project</h3><p>Since this article is the third in the Node.js series we will be building on the last article titled “<a href="https://medium.com/dev-genius/how-to-create-a-dockerized-environment-for-developing-and-testing-node-js-apis-b9e4c22cf464">How to Create a Dockerized Environment for Developing and Testing Node.js APIs</a>”. If you’ve been following along, this is where it gets exciting!</p><p>If you haven’t already set up your Dockerized Node.js API project or need a refresher, not to worry — we’ll get you up to speed in no time. We’ll start by cloning the project from the GitHub repository</p><p>Open up your terminal or command prompt and navigate to the directory where you want to clone the project. Once you’re in the right place, run the following command:</p><pre>git clone https://github.com/hendurhance/express-dockerize</pre><h3>Setting Up the Project</h3><p>1. Once the repository is cloned, navigate into the project directory using the terminal or command prompt:</p><pre>cd express-dockerize</pre><p><strong>2. Installing Dependencies:</strong> Install the packages by running:</p><pre>npm install</pre><p>Or if you use yarn:</p><pre>yarn install</pre><p>There are also a few things you should do before the project can run smoothly, head to <a href="https://medium.com/dev-genius/how-to-create-a-dockerized-environment-for-developing-and-testing-node-js-apis-b9e4c22cf464">How to Create a Dockerized Environment for Developing and Testing Node.js APIs</a> and add what’s missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yE6YGHsrrnr10OrI" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Installing Jest as a testing framework</h3><p>Now that our project is set up, let’s add Jest to our project so we can start writing tests for our Node.js APIs. Jest, as you may recall, is a fantastic testing framework that makes writing and running tests easy.</p><p>To install Jest, simply run the following command in your terminal:</p><pre>npm install jest supertest --save-dev</pre><p>or with yarn:</p><pre>yarn add --dev jest supertest</pre><h3>Properly Configure Jest for Our Project</h3><p>To ensure Jest is configured properly with our existing project, follow the steps below. We’ll begin by installing the necessary dependencies, and then proceed to set up configuration files that will tell Jest how to process our files for testing.</p><p><strong>Step 1: Installing Dependencies</strong></p><p>You can use either npm or Yarn to install the required packages. These include <strong>jest-mock-express</strong> mocking Express.js behavior in tests, and Babel dependencies (<strong>@babel/core</strong>, <strong>@babel/preset-env</strong>, <strong>babel-jest</strong>) for transpiling our ES6 code to a format Jest can understand.</p><pre>npm install jest-mock-express <br>npm install --save-dev @babel/core @babel/preset-env babel-jest</pre><p>or with yarn:</p><pre>yarn add jest-mock-express <br>yarn add --dev @babel/core @babel/preset-env babel-jest</pre><p><strong>Step 2: Configuring Babel</strong></p><p>Create a Babel configuration file named <strong>babel.config.cjs</strong>. This configuration specifies that Babel should use the <strong>@babel/preset-env</strong> to compile our JavaScript code. The <strong>.cjs</strong> extension indicates that the configuration is in CommonJS which is for ES6 modules projects.</p><pre>// **babel.config.cjs**:<br>module.exports = {<br>    presets: [&#39;@babel/preset-env&#39;],<br>};</pre><p><strong>Step 3: Setting Up Jest Configuration</strong></p><p>Next, we need to create a Jest configuration file called <strong>jest.config.cjs</strong>. This file tells Jest on how to transform JavaScript files using Babel, recognizes both <strong>.js</strong> or <strong>.jsx</strong> extensions, and defines the regex pattern to locate test files.</p><pre>// jest.config.cjs:<br>module.exports = {<br>  transform: {<br>    &#39;^.+\\\\.jsx?$&#39;: &#39;babel-jest&#39;  // Transforms JS and JSX files using babel-jest<br>  },<br>  testRegex: &#39;(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.jsx?$&#39;,  // Regex for finding test files<br>  moduleFileExtensions: [&#39;js&#39;, &#39;jsx&#39;, &#39;json&#39;, &#39;node&#39;]  // Supported file extensions<br>};</pre><p><strong>Step 4: Updating the </strong><strong>package.json File</strong></p><p>Modify your <strong>package.json</strong> to include a test script that sets the environment variable <strong>NODE_ENV</strong> to &#39;test&#39;. This ensures that our test environment is separate from the default environment (development), influencing how configurations like databases behave during tests.</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;NODE_ENV=test jest --config jest.config.cjs&quot;,<br>  &quot;start&quot;: &quot;node -r dotenv/config src/app.js&quot;<br>}</pre><p><strong>Step 5: Modifying the </strong><strong>Sale Model for Test Environment</strong> When integrating Jest into a project that uses Sequelize for database operations, it&#39;s important to ensure that Sequelize&#39;s synchronization method <strong>db.sync()</strong> does not automatically run during tests. We can do this by checking the <strong>NODE_ENV</strong> environment variable to prevent database modifications during test execution.</p><pre>import { Sequelize } from &quot;sequelize&quot;;<br>import { db } from &#39;../util/database.util.js&#39;<br><br>const Sale = db.define(&#39;sales&#39;, {<br>    id: {<br>        type: Sequelize.INTEGER,<br>        autoIncrement: true,<br>        allowNull: false,<br>        primaryKey: true<br>    },<br>    customer: {<br>        type: Sequelize.STRING,<br>        allowNull: false<br>    },<br>    product: {<br>        type: Sequelize.STRING,<br>        allowNull: false<br>    },<br>    price: {<br>        type: Sequelize.FLOAT,<br>        allowNull: false<br>    },<br>    address: {<br>        type: Sequelize.STRING,<br>        allowNull: false<br>    },<br>    createdAt: {<br>        type: Sequelize.DATE,<br>        allowNull: false,<br>        field: &#39;createdat&#39;<br>    },<br>    updatedAt: {<br>        type: Sequelize.DATE,<br>        allowNull: false,<br>        field: &#39;updatedat&#39;<br>    }<br>},{<br>    underscored: true,<br>});<br>if (process.env.NODE_ENV !== &#39;test&#39;) {<br>    db.sync().then(() =&gt; {<br>        console.log(&#39;Database &amp; tables created!&#39;);<br>    }).catch(err =&gt; {<br>        console.log(err);<br>    });<br>}<br>export default Sale;</pre><h3>Writing Your First Jest Test</h3><p>In this section, we’ll cover the basics of setting up our test environment, writing a simple test for one of our API endpoints, and running our test suite to ensure everything works</p><p><strong>1. Setting up a basic test file structure</strong></p><p>Let’s start by organizing our test files in a structured manner. Create a new directory named <strong>__tests__</strong> at the root of your project. This directory will house all our test files.</p><p>Inside the <strong>__tests__</strong> directory, create a new file named sales.controller.**test.js ,** sale.test.js and database.util.test.js respectively. This file will contain our test suite for the Sales API Controller, Sale Model, and Database utility file.</p><p>Your directory structure should now look something like this:</p><pre>express-dockerize/<br>├── Dockerfile<br>├── README.md<br>├── babel.config.cjs<br>├── docker-compose.yml<br>├── jest.config.cjs<br>├── package-lock.json<br>├── package.json<br>└── src<br>    ├── __tests__<br>    ├── app.js<br>    ├── controllers<br>    │   ├── sales.controller.js<br>    │   └── sales.controller.test.js<br>    ├── database<br>    │   └── sales.sql<br>    ├── models<br>    │   ├── sale.js<br>    │   └── sale.test.js<br>    ├── routes<br>    │   └── sales.routes.js<br>    └── util<br>        ├── database.util.js<br>        └── database.util.test.js</pre><p><strong>2. Implementing the Test Suite</strong></p><h4>Database Utility File</h4><p>Once your test file is set up, it’s time to implement the tests. We’ll be starting with our database.util.test.js</p><pre>import { db } from &#39;./database.util&#39;;<br><br>describe(&#39;Database Util&#39;, () =&gt; {<br>  it(&#39;should create a new Sequelize instance&#39;, () =&gt; {<br>    expect(db).toBeDefined();<br>    expect(db.constructor.name).toBe(&#39;Sequelize&#39;);<br>  });<br>  it(&#39;should have the correct database configuration&#39;, () =&gt; {<br>    const { options } = db;<br>    expect(options.host).toBe(process.env.DB_HOST);<br>    expect(options.port).toBe(process.env.DB_PORT);<br>    expect(options.dialect).toBe(&#39;postgres&#39;);<br>  });<br>});</pre><p>The first test ensures that the <strong>db</strong> object, representing our Sequelize instance, is properly instantiated and not undefined, confirming that the Sequelize module was correctly imported and initialized. It further checks that this object is indeed an instance of Sequelize, which is crucial for all database operations. The second test verifies that the <strong>db</strong> instance is configured with the correct connection parameters such as host, port, and dialect by comparing these properties to the expected values, which are stored in environment variables. This test suite ensures that the application connects to the correct database with appropriate variables.</p><h4>Sale Model File</h4><p>The next text suite is sales.test.js which is our model file:</p><pre>import { db } from &#39;../util/database.util&#39;;<br>import Sale from &#39;./sale&#39;; // Import the Sale model<br><br>describe(&#39;Sale Model&#39;, () =&gt; {<br>    beforeAll(async () =&gt; {<br>        await db.sync(); // Sync the database before running the tests<br>    });<br>    afterEach(async () =&gt; {<br>        await Sale.destroy({ where: {} }); // Delete all records after each test<br>    });<br>    afterAll(async () =&gt; {<br>        await db.close(); // Close the database connection after running the tests<br>    });<br>    it(&#39;should create a new sale&#39;, async () =&gt; {<br>        const saleData = {<br>            customer: &#39;John Doe&#39;,<br>            product: &#39;Product A&#39;,<br>            price: 10.99,<br>            address: &#39;123 Main St&#39;,<br>            createdAt: new Date(),<br>            updatedAt: new Date(),<br>        };<br>        const sale = await Sale.create(saleData);<br>        expect(sale).toBeDefined();<br>        expect(sale.customer).toBe(saleData.customer);<br>        expect(sale.product).toBe(saleData.product);<br>        expect(sale.price).toBe(saleData.price);<br>        expect(sale.address).toBe(saleData.address);<br>        expect(new Date(sale.createdAt).toUTCString()).toBe(new Date(saleData.createdAt).toUTCString());<br>        expect(new Date(sale.updatedAt).toUTCString()).toBe(new Date(saleData.updatedAt).toUTCString());       <br>    });<br>    it(&#39;should retrieve all sales&#39;, async () =&gt; {<br>        const saleData1 = {<br>            customer: &#39;John Doe&#39;,<br>            product: &#39;Product A&#39;,<br>            price: 10.99,<br>            address: &#39;123 Main St&#39;,<br>            createdAt: new Date(),<br>            updatedAt: new Date(),<br>        };<br>        const saleData2 = {<br>            customer: &#39;Jane Smith&#39;,<br>            product: &#39;Product B&#39;,<br>            price: 19.99,<br>            address: &#39;456 Elm St&#39;,<br>            createdAt: new Date(),<br>            updatedAt: new Date(),<br>        };<br>        await Sale.create(saleData1);<br>        await Sale.create(saleData2);<br>        const sales = await Sale.findAll();<br>        expect(sales).toHaveLength(2);<br>        expect(sales[0].customer).toBe(saleData1.customer);<br>        expect(sales[1].customer).toBe(saleData2.customer);<br>    });<br>    it(&#39;should retrieve a sale by ID&#39;, async () =&gt; {<br>        const saleData = {<br>            customer: &#39;John Doe&#39;,<br>            product: &#39;Product A&#39;,<br>            price: 10.99,<br>            address: &#39;123 Main St&#39;,<br>            createdAt: new Date(),<br>            updatedAt: new Date(),<br>        };<br>        const { id } = await Sale.create(saleData);<br>        const sale = await Sale.findByPk(id);<br>        expect(sale).toBeDefined();<br>        expect(sale.customer).toBe(saleData.customer);<br>        expect(sale.product).toBe(saleData.product);<br>        expect(sale.price).toBe(saleData.price);<br>        expect(sale.address).toBe(saleData.address);<br>        expect(sale.createdAt.toISOString()).toBe(saleData.createdAt.toISOString());<br>        expect(sale.updatedAt.toISOString()).toBe(saleData.updatedAt.toISOString());<br>    });<br>    it(&#39;should update a sale by ID&#39;, async () =&gt; {<br>        const saleData = {<br>            customer: &#39;John Doe&#39;,<br>            product: &#39;Product A&#39;,<br>            price: 10.99,<br>            address: &#39;123 Main St&#39;,<br>            createdAt: new Date(),<br>            updatedAt: new Date(),<br>        };<br>        const { id } = await Sale.create(saleData);<br>        const newSaleData = {<br>            customer: &#39;Jane Smith&#39;,<br>            product: &#39;Product B&#39;,<br>            price: 19.99,<br>            address: &#39;456 Elm St&#39;,<br>        };<br>        const [rowsUpdated] = await Sale.update(newSaleData, { where: { id } });<br>        expect(rowsUpdated).toBe(1);<br>        const sale = await Sale.findByPk(id);<br>        expect(sale).toBeDefined();<br>        expect(sale.customer).toBe(newSaleData.customer);<br>        expect(sale.product).toBe(newSaleData.product);<br>        expect(sale.price).toBe(newSaleData.price);<br>        expect(sale.address).toBe(newSaleData.address);<br>    });<br>    it(&#39;should delete a sale by ID&#39;, async () =&gt; {<br>        const saleData = {<br>            customer: &#39;John Doe&#39;,<br>            product: &#39;Product A&#39;,<br>            price: 10.99,<br>            address: &#39;123 Main St&#39;,<br>            createdAt: new Date(),<br>            updatedAt: new Date(),<br>        };<br>        const { id } = await Sale.create(saleData);<br>        const deletedSale = await Sale.destroy({ where: { id } });<br>        expect(deletedSale).toBe(1);<br>        const sale = await Sale.findByPk(id);<br>        expect(sale).toBeNull();<br>    });<br>});</pre><p>The suite starts out by setting up the database environment, ensuring each test starts with a synchronized database schema and concludes with a closed database connection to prevent resource leakage. It includes all CRUD operations: creating, reading, updating, and deleting sales entries. Each test is designed to verify the integrity and correctness of database interactions. For example, it checks if new sales are correctly added and retrievable, existing sales can be updated accurately, and unwanted records can be deleted, ensuring no records are left behind. Such detailed testing ensures the application’s database layer functions reliably, maintaining data accuracy and system stability, which is crucial for any data-driven application.</p><h4>Sales Controller File</h4><p>The last file is sales.controller.test.js which is implemented by the route file and serves as a connection between the route and the database layer of the app.</p><pre>import { getAllSales, getSaleById, createSale } from &#39;./sales.controller&#39;;<br>import Sale from &#39;../models/sale&#39;;<br><br>// Mocking Sale model methods<br>jest.mock(&#39;../models/sale&#39;, () =&gt; ({<br>    findAll: jest.fn(),<br>    findByPk: jest.fn(),<br>    create: jest.fn(),<br>}));<br>describe(&#39;Sales Controller&#39;, () =&gt; {<br>    let req, res;<br>    beforeEach(() =&gt; {<br>        // Manually mocking req and res if jest-mock-express import fails<br>        req = { params: {}, body: {} };<br>        res = { json: jest.fn(), status: jest.fn().mockReturnThis() };<br>    });<br>    // Example test for getAllSales<br>    it(&#39;should return all sales with a 200 status code&#39;, async () =&gt; {<br>        const sales = [{ id: 1, customer: &#39;John Doe&#39;, product: &#39;Widget&#39;, price: 100, address: &#39;123 Street&#39; }];<br>        Sale.findAll.mockResolvedValue(sales);<br>        await getAllSales(req, res);<br>        expect(res.status).toHaveBeenCalledWith(200);<br>        expect(res.json).toHaveBeenCalledWith({ data: sales });<br>    });<br>    describe(&#39;getAllSales&#39;, () =&gt; {<br>        it(&#39;should return all sales with a 200 status code&#39;, async () =&gt; {<br>            const sales = [<br>                { id: 1, customer: &#39;John Doe&#39;, product: &#39;Widget&#39;, price: 100, address: &#39;123 Street&#39; },<br>                { id: 2, customer: &#39;Jane Doe&#39;, product: &#39;Gadget&#39;, price: 150, address: &#39;456 Avenue&#39; },<br>            ];<br>            Sale.findAll.mockResolvedValue(sales);<br>            await getAllSales(req, res);<br>            expect(res.status).toHaveBeenCalledWith(200);<br>            expect(res.json).toHaveBeenCalledWith({ data: sales });<br>        });<br>    });<br>    describe(&#39;getSaleById&#39;, () =&gt; {<br>        it(&#39;should return a sale by id with a 200 status code&#39;, async () =&gt; {<br>            const sale = { id: 1, customer: &#39;John Doe&#39;, product: &#39;Widget&#39;, price: 100, address: &#39;123 Street&#39; };<br>            Sale.findByPk.mockResolvedValue(sale);<br>            req.params.id = 1;<br>            await getSaleById(req, res);<br>            expect(res.status).toHaveBeenCalledWith(200);<br>            expect(res.json).toHaveBeenCalledWith({ data: sale });<br>        });<br>        it(&#39;should return a 404 status code if sale is not found&#39;, async () =&gt; {<br>            Sale.findByPk.mockResolvedValue(null);<br>            req.params.id = 1;<br>            await getSaleById(req, res);<br>            expect(res.status).toHaveBeenCalledWith(404);<br>            expect(res.json).toHaveBeenCalledWith({ message: &#39;Sale not found&#39; });<br>        });<br>    });<br>    describe(&#39;getSaleById&#39;, () =&gt; {<br>        beforeEach(() =&gt; {<br>            req.params.id = 1; // Assuming we&#39;re looking for the sale with ID 1<br>        });<br>    <br>        it(&#39;should return a sale by ID with a 200 status code&#39;, async () =&gt; {<br>            const sale = { id: 1, customer: &#39;John Doe&#39;, product: &#39;Widget&#39;, price: 100, address: &#39;123 Street&#39; };<br>            Sale.findByPk.mockResolvedValue(sale);<br>    <br>            await getSaleById(req, res);<br>    <br>            // Using an integer here as it seems the `findByPk` is being called with an integer<br>            expect(Sale.findByPk).toHaveBeenCalledWith(1);<br>            expect(res.status).toHaveBeenCalledWith(200);<br>            expect(res.json).toHaveBeenCalledWith({ data: sale });<br>        });<br>    <br>        it(&#39;should return 404 if the sale is not found&#39;, async () =&gt; {<br>            Sale.findByPk.mockResolvedValue(null);<br>    <br>            await getSaleById(req, res);<br>    <br>            // Again, using an integer to match the actual type being passed<br>            expect(Sale.findByPk).toHaveBeenCalledWith(1);<br>            expect(res.status).toHaveBeenCalledWith(404);<br>            expect(res.json).toHaveBeenCalledWith({ message: &#39;Sale not found&#39; });<br>        });<br>    });<br>    <br>    <br>    describe(&#39;createSale&#39;, () =&gt; {<br>        beforeEach(() =&gt; {<br>            req.body = { customer: &#39;Jane Doe&#39;, product: &#39;Gadget&#39;, price: 150, address: &#39;456 Avenue&#39; };<br>        });<br>    <br>        it(&#39;should create a sale and return 201&#39;, async () =&gt; {<br>            const newSale = { ...req.body, id: 2 };<br>            Sale.create.mockResolvedValue(newSale);<br>    <br>            await createSale(req, res);<br>    <br>            expect(Sale.create).toHaveBeenCalledWith(req.body);<br>            expect(res.status).toHaveBeenCalledWith(201);<br>            expect(res.json).toHaveBeenCalledWith({ data: newSale });<br>        });<br>    <br>        it(&#39;should return 400 if a required field is missing&#39;, async () =&gt; {<br>            req.body = { customer: &#39;Jane Doe&#39;, product: &#39;Gadget&#39;, price: 150 }; // Address is missing<br>    <br>            await createSale(req, res);<br>    <br>            expect(res.status).toHaveBeenCalledWith(400);<br>            expect(res.json).toHaveBeenCalledWith({ message: &#39;All fields are required&#39; });<br>        });<br>    <br>        it(&#39;should handle errors with a 500 status code&#39;, async () =&gt; {<br>            Sale.create.mockRejectedValue(new Error(&#39;Database error&#39;));<br>    <br>            await createSale(req, res);<br>    <br>            expect(Sale.create).toHaveBeenCalledWith(req.body);<br>            expect(res.status).toHaveBeenCalledWith(500);<br>            expect(res.json).toHaveBeenCalledWith({ error: &#39;Database error&#39; });<br>        });<br>    });<br>});</pre><p>This Jest test suite focuses on the interactions with a Sequelize model for CRUD operations. The tests simulate various scenarios for the controller’s endpoints, including fetching all sales, retrieving a specific sale by ID, creating a new sale, and error handling, such as missing fields or database errors. By mocking the Sale model’s methods (findAll, findByPk, create), the suite ensures that database operations do not execute, thus isolating the controller logic for testing. This allows each test to control the expected outcomes and verify that the controller responds correctly, for instance, returning all sales with a 200 status, handling not found errors with a 404 status, and confirming the successful creation of sales with a 201 status. The suite also checks for proper error responses when required fields are missing or when a server error occurs during sale creation. This testing approach ensures that the sales controller behaves as expected under various data and error conditions, enhancing the reliability and robustness of the application’s data access layer.</p><p><strong>3. Running the Test Suite</strong></p><p>To run your test suite, execute the following command in your terminal:</p><pre>npm test</pre><p>or if you are using Yarn:</p><pre>yarn test</pre><p>This will initiate Jest, which will find and run the tests specified in your database.util.test.js , sale.js and <strong>sales.controller.test.js</strong> file, providing you with feedback on whether the tests passed or failed.</p><h3>Conclusion</h3><p>To conclude, leveraging Jest for testing your Node.js API is just like using Airtags to search for lost items, Jest makes debugging the debugging process for your API easy. It offers a structured and efficient way to ensure every function performs as expected and every unexpected error is caught before it can cause issues in production. We’ve walked through setting up Jest, creating tests for various API endpoints, and ensuring our code integrity through mock implementations. Now, knowing with these tools, you’re better prepared to develop reliable, robust applications. Happy bug hunting — and here’s hoping your debugging days are as short as a 30-second Airtag search!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b878738a833" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-integrate-jest-into-your-node-js-api-development-for-better-test-coverage-6b878738a833">How to Integrate Jest into Your Node.js API Development for Better Test Coverage</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Databases: Comprehensive Guide to PostgreSQL]]></title>
            <link>https://blog.devgenius.io/introduction-to-databases-comprehensive-guide-to-postgresql-f89b3d54c2a9?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89b3d54c2a9</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 09:31:44 GMT</pubDate>
            <atom:updated>2024-02-15T16:29:33.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6AQQqQs8Do9fHaDj" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=medium&amp;utm_medium=referral">Jan Antonin Kolar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever felt you’re lost in a maze with no map?</p><p>Imagine you bust into a public library, surrounded by towering shelves of books where every aisle seems to lead to more confusion than clarity. You have a burning desire to find a book, but it’s like searching for a needle in a haystack. The day is not yet lost, picture a librarian swopped in with a brilliant solution, organizing every book into neat sections, each labeled and categorized for easy access. That’s the magic of a database — it’s almost like having a very good librarian at your fingertips!</p><p>Today, databases are a core part of our everyday life. Whether you’re scrolling through your favorite social media feed, managing your finances online, or simply booking a movie ticket, databases are silently working behind the scenes, storing, organizing, and retrieving data to ensure the smooth functioning of applications we interact with daily.</p><h3>Understanding Databases</h3><p>At its core, a database is simply a structured collection of data stored electronically in a computer system. According to Oracle:</p><blockquote><em>A database is </em><strong><em>an organized collection of structured information, or data, typically stored electronically in a computer system</em></strong><em>.</em></blockquote><p>Looking at the instance of well well-organized library we gave at the introduction of the article, databases are quite similar which makes it easy to find certain data and and manipulate it. But databases aren’t just static repositories; they’re dynamic entities managed by sophisticated software known as Database Management Systems (DBMS). These systems are responsible for efficiently storing, retrieving, and managing data while ensuring its integrity and security.</p><h3>Purpose of Databases</h3><p>Imagine you’re running an online store. You need a system to keep track of your products, customers, and orders. Here’s where a database comes into play. By using a database, you can efficiently store product details, manage customer information, and process orders seamlessly. Whether it’s handling inventory, generating invoices, or analyzing sales trends, databases serve as the backbone of various applications, ensuring they run smoothly and reliably.</p><h3>Types of Databases</h3><p>Databases come in different types, each catering to specific needs:</p><ol><li><strong>Relational Databases (RDBMS)</strong>: These are like digital spreadsheets kind of like Microsoft Excel, organizing data into tables with defined relationships. Think of it as a series of interconnected tables where each row represents a record, and each column represents a specific attribute. Popular examples include PostgreSQL, MySQL, and Oracle.</li><li><strong>NoSQL Databases</strong>: Unlike traditional relational databases, NoSQL databases offer more flexibility in handling diverse data models. They’re ideal for scenarios where the data structure is constantly evolving or where scalability is a priority. MongoDB and Cassandra are popular examples in this category.</li></ol><h3>Key Concepts in Databases</h3><p>To navigate the world of databases, it’s essential to grasp some fundamental concepts:</p><ol><li><strong>Tables</strong>: Data in a relational database is organized into tables, resembling spreadsheets. Each table consists of rows and columns, with each row representing a unique record and each column denoting a specific attribute.</li><li><strong>Schema</strong>: The schema defines the structure and constraints of the data within a database. It outlines the layout of tables, specifying the data types, relationships, and rules governing the data.</li><li><strong>Queries</strong>: Queries are requests made to the database to retrieve or manipulate data. They allow users to extract insights, perform calculations, and update records based on specific criteria.</li><li><strong>Transactions</strong>: Transactions are a fundamental unit of work in a database. They consist of a series of operations executed as a single unit to maintain data integrity. Transactions follow the ACID properties, ensuring Atomicity, Consistency, Isolation, and Durability.</li></ol><h3>Why PostgreSQL?</h3><p>With so many databases available, why should you give PostgreSQL a try? Imagine yourself at a bustling tech conference, surrounded by booths touting the latest and greatest innovations. It’s easy to get swept up in the hype, but when it comes down to it, you need a solution that’s not just flashy, but also dependable and adaptable. That’s where Postgres steps in, think of it as a speaker commanding the stage with authority and grace, PostgreSQL has earned its place as a top contender in the world database. Let’s dive into more features Postgres boast of:</p><p><strong>1. Robust Features</strong>: PostgreSQL boasts a rich feature set, including ACID compliance, transactional integrity, support for complex queries, and advanced data types. Whether you’re handling massive datasets or intricate operations, PostgreSQL offers the tools you need.</p><ul><li><strong>Atomicity</strong> — each statement in a transaction (to read, write, update, or delete data) is treated as a single unit. Either the entire statement is executed, or none of it is executed. This property prevents data loss and corruption from occurring if, for example, your streaming data source fails mid-stream.</li><li><strong>Consistency</strong> — ensures that transactions only make changes to tables in predefined, predictable ways. Transactional consistency ensures that corruption or errors in your data do not create unintended consequences for the integrity of your table.</li><li><strong>Isolation</strong> — when multiple users are reading and writing from the same table all at once, isolation of their transactions ensures that the concurrent transactions don’t interfere with or affect one another. Each request can occur as though they were occurring one by one, even though they’re occurring simultaneously.</li><li><strong>Durability</strong> — ensures that changes to your data made by successfully executed transactions will be saved, even in the event of system failure.</li></ul><p><strong>2. Community Support</strong>: With a vibrant community of developers and users, PostgreSQL enjoys strong community support. This means timely updates, extensive documentation, and a wealth of resources to aid users at every step.</p><p><strong>3. Cross-Platform Compatibility</strong>: PostgreSQL is compatible with various operating systems, making it accessible across different environments. Whether you’re on Windows, Linux, or macOS, you can seamlessly integrate PostgreSQL into your infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*50AGc9KWysi9FY2H2aPlOg.png" /></figure><h3>Installing PostgreSQL on Your Local Machine</h3><p>Regardless of whether you’re on Windows, Linux, or macOS, downloading and installing PostgreSQL is a breeze.</p><p><strong>For Windows:</strong></p><ol><li><strong>Download PostgreSQL Installer:</strong> Visit the official PostgreSQL website at <a href="https://www.postgresql.org/download/windows/">https://www.postgresql.org/download/windows/</a> and download the installer for your Windows version (32-bit or 64-bit).</li><li><strong>Run the Installer:</strong> Once the download is complete, double-click the downloaded installer file to launch the PostgreSQL Setup Wizard.</li><li><strong>Choose Installation Directory:</strong> Follow the prompts of the Setup Wizard, choosing the installation directory and components you wish to install. By default, PostgreSQL will be installed in <strong>C:\\Program Files\\PostgreSQL</strong>.</li><li><strong>Set Password:</strong> During the installation process, you’ll be prompted to set a password for the default <strong>postgres</strong> user. Make sure to remember this password as it will be required for database administration tasks.</li><li><strong>Complete Installation:</strong> After configuring the installation options, click “Next” to begin the installation process. Once completed, click “Finish” to exit the Setup Wizard.</li><li><strong>Verify Installation:</strong> To verify that PostgreSQL is installed correctly, open the Start menu and search for “pgAdmin”. Launch pgAdmin, the PostgreSQL graphical administration tool. If it opens without errors, PostgreSQL has been successfully installed on your Windows machine.</li></ol><p><strong>For macOS:</strong></p><ol><li><strong>Download PostgreSQL App:</strong> Visit <a href="https://postgresapp.com/">https://postgresapp.com/</a> and download the PostgreSQL App for macOS.</li><li><strong>Install PostgreSQL App:</strong> Once the download is complete, open the downloaded <strong>.dmg</strong> file and drag the PostgreSQL icon to the Applications folder.</li><li><strong>Start PostgreSQL:</strong> Open the Applications folder, locate the PostgreSQL App, and double-click to launch it. This will start the PostgreSQL server on your macOS machine.</li><li><strong>Verify Installation:</strong> To verify that PostgreSQL is running correctly, look for the elephant icon in the menu bar. If it’s there, PostgreSQL is up and running on your macOS machine.</li></ol><p><strong>For Linux:</strong></p><ol><li><strong>Use Package Manager:</strong> Most Linux distributions come with PostgreSQL available in their package repositories. Use your distribution’s package manager to install PostgreSQL. For example, on Ubuntu, you can run <strong>sudo apt-get install postgresql</strong>.</li><li><strong>Start PostgreSQL Service:</strong> Once PostgreSQL is installed, the service should start automatically. If not, you can start it manually using a command like <strong>sudo service postgresql start</strong> or <strong>sudo systemctl start postgresql</strong>.</li><li><strong>Set Password:</strong> By default, PostgreSQL creates a user name <strong>postgres</strong> with no password. You can set a password for this user by running <strong>sudo -u postgres psql postgres</strong> and then entering <strong>\\password</strong> to set the password.</li><li><strong>Verify Installation:</strong> To verify that PostgreSQL is installed and running correctly, you can connect to the PostgreSQL server using the <strong>psql</strong> command-line tool or by using a graphical interface like pgAdmin.</li></ol><h3>Basic Commands in PostgreSQL</h3><p>We’ll cover essential concepts, practical examples, and best practices to help you get started with building and managing databases effectively.</p><p><strong>Connecting to a Database</strong></p><ul><li><strong>psql Command Line Tool (All Platforms):</strong> Open your terminal or command prompt and type <strong>psql -U username -d database_name</strong>. Replace <strong>username</strong> with your PostgreSQL username and <strong>database_name</strong> with the name of the database you want to connect to. If your PostgreSQL server is running on a different host or port, use the <strong>h</strong> and <strong>p</strong> flags respectively.</li><li><strong>pgAdmin (GUI Tool):</strong> Launch pgAdmin and connect to your PostgreSQL server by providing the necessary connection details like host, port, username, and password. Once connected, you can navigate through the databases and interact with them using a graphical interface.</li></ul><p><strong>Creating a Database</strong></p><p>Let’s start by creating a new database. Open your terminal or command prompt and enter the following command:</p><pre>CREATE DATABASE my_database;</pre><p>This command creates a new database named <strong>my_database</strong>. You can replace <strong>my_database</strong> with your desired name.</p><p><strong>Connecting to the Database</strong></p><p>Next, connect to the newly created database using the following command:</p><pre>\\c my_database;</pre><p>This command establishes a connection to the <strong>my_database</strong> database.</p><p><strong>Creating Tables</strong></p><p>Now, let’s create two tables: <strong>students</strong> and <strong>courses</strong>. We&#39;ll define the structure of each table along with appropriate data types and constraints.</p><pre>CREATE TABLE students (<br>    student_id SERIAL PRIMARY KEY,<br>    first_name VARCHAR(50),<br>    last_name VARCHAR(50),<br>    email VARCHAR(100) UNIQUE<br>);<br><br>CREATE TABLE courses (<br>    course_id SERIAL PRIMARY KEY,<br>    course_name VARCHAR(100),<br>    instructor VARCHAR(100),<br>    credits INT<br>);</pre><p>Here’s a breakdown of the table creation commands:</p><ul><li>We use the <strong>CREATE TABLE</strong> statement followed by the table name.</li><li>Each table consists of columns, each with a name and data type.</li><li>Primary keys are specified using the <strong>PRIMARY KEY</strong> constraint.</li><li>Additional constraints such as <strong>UNIQUE</strong> are used to enforce data integrity.</li></ul><p><strong>Inserting Data</strong></p><p>Let’s add some sample data into the <strong>students</strong> and <strong>courses</strong> tables using <strong>INSERT</strong> statements.</p><pre>INSERT INTO students (first_name, last_name, email)<br>VALUES (&#39;John&#39;, &#39;Doe&#39;, &#39;john@example.com&#39;);<br>INSERT INTO students (first_name, last_name, email)<br>VALUES (&#39;Jane&#39;, &#39;Smith&#39;, &#39;jane@example.com&#39;);<br>INSERT INTO courses (course_name, instructor, credits)<br>VALUES (&#39;Introduction to Programming&#39;, &#39;Dr. Smith&#39;, 3);<br>INSERT INTO courses (course_name, instructor, credits)<br>VALUES (&#39;Database Management&#39;, &#39;Prof. Johnson&#39;, 4);</pre><p>These <strong>INSERT</strong> statements add records to the <strong>students</strong> and <strong>courses</strong> tables, providing values for each column.</p><p><strong>Selecting Data</strong></p><p>To retrieve data from the tables, we use <strong>SELECT</strong> statements. Here are some examples:</p><pre>-- Select all columns from the students table<br>SELECT * FROM students;<br><br>-- Select specific columns from the courses table<br>SELECT course_name, instructor FROM courses;</pre><p><strong>Updating Data</strong></p><p>To modify existing records, we use <strong>UPDATE</strong> statements. Let&#39;s update a student&#39;s email address:</p><pre>UPDATE students<br>SET email = &#39;john.doe@example.com&#39;<br>WHERE student_id = 1;</pre><p>This command changes the email address of the student with <strong>student_id</strong> 1.</p><p><strong>Deleting Data</strong></p><p>To remove records from a table, we use <strong>DELETE</strong> statements. Let&#39;s delete a student from the <strong>students</strong> table:</p><pre>DELETE FROM students<br>WHERE student_id = 2;</pre><p>This command deletes the student with <strong>student_id</strong> 2 from the <strong>students</strong> table.</p><h3>Naming Conventions</h3><p>It’s essential to follow naming conventions for consistency and clarity. Here are some guidelines:</p><ul><li>Table names should be descriptive and plural (e.g., <strong>students</strong>, <strong>courses</strong>).</li><li>Column names should be singular and descriptive (e.g., <strong>student_id</strong>, <strong>course_name</strong>).</li><li>Use lowercase letters and underscores for multi-word names (e.g., <strong>first_name</strong>, <strong>course_id</strong>).</li><li>Avoid using reserved keywords as names to prevent conflicts.</li></ul><h3><strong>Conclusion</strong></h3><p>In today’s data-driven world, databases like PostgreSQL play a pivotal role in powering our digital experiences. Whether you’re managing an online business, analyzing customer behavior, or simply browsing the web, databases silently work behind the scenes, ensuring seamless operation and reliable data management. By understanding the basics of databases and leveraging powerful tools like PostgreSQL, you can unlock a world of possibilities in data management and application development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89b3d54c2a9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/introduction-to-databases-comprehensive-guide-to-postgresql-f89b3d54c2a9">Introduction to Databases: Comprehensive Guide to PostgreSQL</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Spontaneity to Predictability: The Statistical Takeover of Modern Life]]></title>
            <link>https://medium.com/@hendurhance/from-spontaneity-to-predictability-the-statistical-takeover-of-modern-life-4dc0aad4dbd7?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc0aad4dbd7</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 08:31:45 GMT</pubDate>
            <atom:updated>2024-02-13T08:31:45.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dc0M8mvYYVsXrC3z" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A few days ago, a large percentage of us watched the AFCON final between Nigeria and Ivory Coast, if you didn’t you probably watched a Premier League game or the Super Bowl. During the football match, one can’t help but notice the fast heart rates, palpable tensions, the crowd roaring, and suddenly… wait, hold that thought for a second. Before you even finish the scene in your head, let’s take a step back and analyze the match, shall we? How many chances were created? What’s the possession like? How do the expected goals of team A stack up against team B? Yes, statistics — the numbers game that seems to be infiltrating every aspect of our lives, from sports to shopping and basically everything in between</p><p>I know what you are thinking, don’t get me wrong, I’m all for a good set of data. Fun fact, I’m a current Statistics and Data Science major, and I’m no stranger to the world of data I mean, who doesn’t love a nice pie chart or a juicy bar graph? A good heat map on your favourite player? But, lately, it seems statistics are taking over, and with it the spontaneity that makes life so exciting.</p><p>Consider football, for instance. In the glorious era of the 2010s (which I fondly remember), watching a match was an exhilarating experience marked by suspense and unpredictability, except for the GOATs for sure, you know the ball is likely ending at the back of the net. Fast forward to today, and the narrative has shifted. The focus has shifted from the thrill of the game to the cold analysis of statistics — goals, pass completion rates, duels won. It’s like watching a game of FIFA on repeat, minus the controller and the snacks.</p><p>And let’s not even begin to discuss the immense pressure it heaps upon the players. Picture yourself as a striker, each missed shot or misplaced pass subject to relentless scrutiny and analysis. The weight of expectation hangs heavy on your shoulders, knowing that every move you make will be dissected by pundits and fans alike.</p><p>Midfielders, too, find themselves tied in the same statistical web. Expected to make up to 100 passes in a single game, create numerous scoring opportunities, and orchestrate the transition from defense to attack, they are under constant pressure to meet statistical benchmarks. The sheer magnitude of these demands can leave even the most talented players questioning their place on the field. It’s enough to make one consider hanging up their boots and pursuing a quieter, less scrutinized pursuit — perhaps knitting, though it’s unlikely to pay the astronomical wages of professional football.</p><p>But it’s not just sports that are feeling the effect of statistics. Oh no, it’s it’s seeping into every part of our lives. Want to buy a new pair of shoes? Well, there’s a stat for that — from your shoe size to your preferred brand, they’ve got it all figured out. It’s like the algorithms know you better than you know yourself.</p><p>Just the other day, I was chatting with a friend about how Google seems to have its hands on almost every piece of data about us. Think about it — from the moment you created your first Google email account and started using Google Search, they’ve been keeping tabs on you. And let’s not forget about the apps you downloaded from the Google Play Store. Unless you’re an Apple user, Google’s got its eyes on you. And even if you are an Apple fan, don’t think you’re off the hook when it comes to privacy — they’ve got their own ways of collecting data too.</p><p>And don’t even get me started on the dating scene. Thanks to dating apps, finding love has become less about serendipity and more about swiping left or right based on a carefully curated set of stats. Compatibility algorithms claim to know who your soulmate is before you’ve even exchanged a single word. Call me old-fashioned, but I prefer a little mystery with my romance.</p><p>But perhaps the most concerning aspect of this statistical invasion is the threat it poses to our very notion of free will. With AI algorithms getting smarter by the day, who’s to say they won’t soon be able to predict our every move? It’s like living in an episode of Black Mirror, only without the cool futuristic gadgets (whoops, Apple Vision Pro says hi 👋 ). Lately, I’ve been bombarded with ads for AWS Cloud Training to the point where I had to consider if it’s a career path for me. But here’s the kicker — was that decision really mine to make? Or was it simply a result of cause and effect, driven by the relentless targeting of ads? It’s a bit of a mind-boggler, isn’t it?</p><p>I mean, think about it. The world we’re heading towards is starting to resemble something out of the Devs series. Every decision we make seems to have a reason behind it. Take this morning, for example. You wake up craving a cheeseburger. But do you really want that cheeseburger, or is it just because you’ve been bombarded with Burger King ads on your phone? Can we even call that a decision made out of free will, or is it just the result of algorithms influencing our choices? It’s like our spontaneity is being taken away. as algorithms sift through mountains of data to predict what we’ll do next.</p><p>So what’s the solution, you ask? Well, for starters, we could all stand to loosen our grip on the data and embrace the chaos of life. After all, some of the best moments happen when you least expect them — like finding a ten-dollar bill in your pocket or stumbling upon a nice person at the café. So the next time you find yourself reaching for the stats, take a moment to pause and ask yourself: do I really need to know the pass completion rate of every player on the pitch? Or can I just sit back, relax, and enjoy the beautiful game for what it is — a glorious mess of unpredictability and joy? After all, isn’t that what life’s all about?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc0aad4dbd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Dockerized Environment for Developing and Testing Node.js APIs]]></title>
            <link>https://blog.devgenius.io/how-to-create-a-dockerized-environment-for-developing-and-testing-node-js-apis-b9e4c22cf464?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e4c22cf464</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 19:01:38 GMT</pubDate>
            <atom:updated>2024-01-25T17:10:21.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5sYEnTDmwbV-fDlO" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever heard of containerization? If you’re picturing those giant shipping containers, you’re not far off. But instead of goods, we’re shipping software. Containerization is a way to package up an application with everything it needs to run, ensuring it works the same way, no matter where it goes.</p><p>Consider the development of large software applications as a team sport. This often involves multiple individuals rebuilding the same application on different devices — whether it’s a Mac, Windows, or Linux system — which can lead to conflicts. Containerization steps in as our conflict resolver, maintaining consistency by ensuring your software runs with all its required elements intact across every platform.</p><p>Now, let’s turn our attention to Docker, a pivotal player in the world of containerization. This article will guide you through creating a Dockerized environment tailored for your Node.js APIs. Strap in and prepare for a detailed exploration of leveraging Docker to streamline your Node.js API development and testing process!</p><h3>Really, What’s Docker?</h3><p>If you haven’t noticed, we’ve name-dropped “Docker” a few times already, but what exactly it is? In the simplest terms, think of Docker as a virtual suitcase that lets you pack your application with all the tools, along with all the settings and dependencies it needs, into neat, portable containers. These containers can be easily shipped and run anywhere just like we mentioned in the introductory paragraphs, making sure that ‘It works on my machine!’ is no longer an excuse but a guarantee.</p><p>Having understood what Docker is and how it isolates your application from its environment, we can now learn how to install Docker on our machine. The installation process is fairly straightforward and well-documented on <a href="https://www.docker.com/">Docker’s official website</a>. Whether you’re using Windows, macOS, or a Linux distro, you’ll find specific instructions tailored to your operating system. Once you’ve downloaded the installer, it’s typically a matter of a few clicks and agreeing to the terms and conditions (which we all thoroughly read, right?).</p><ul><li>For MacOS: <a href="https://docs.docker.com/desktop/mac/install/">https://docs.docker.com/desktop/mac/install/</a></li><li>For Windows: <a href="https://docs.docker.com/desktop/windows/install/">https://docs.docker.com/desktop/windows/install/</a></li><li>For Linux: <a href="https://docs.docker.com/engine/install/#server">https://docs.docker.com/engine/install/#server</a></li></ul><p>After installation, setting up Docker on your machine usually involves opening a terminal window and running a few basic commands to verify the installation. This might look something like typing docker --version to ensure Docker responds with the version number, indicating a successful setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x1Fzz-luJZ8pN8Jn" /><figcaption>Photo by <a href="https://unsplash.com/@gamell?utm_source=medium&amp;utm_medium=referral">Joan Gamell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building the Node.js API</h3><p>In my last article, titled <a href="https://medium.com/@hendurhance/how-to-build-a-weighted-round-robin-load-balancer-in-node-js-23f3f0364860">“<strong>How to Build a Weighted Round Robin Load Balancer in Node.js”</strong></a>, we used a sales API endpoint that gets data from a CSV file, we are going to create an API that can create, retrieve, and retrieve all sales data from a Postgres Database (for those who don’t know what a Postgres Database is, <a href="https://en.wikipedia.org/wiki/PostgreSQL">check this out</a>)</p><h4>Step 1: Setting Up the Node.js Environment</h4><p>Create a new folder named <strong>express-docker</strong> on your system and navigate into it using the terminal:</p><pre>mkdir express-docker<br>cd express-docker</pre><p>Initialize a new Node.js project:</p><pre>npm init -y</pre><h4>Step 2: Installing Dependencies</h4><p>Install the necessary packages by running:</p><pre>npm install body-parser express pg sequelize<br>npm install dotenv --save-dev</pre><h4>Step 3: Setting Up the Directory Structure</h4><p>Create the following directory structure within the <strong>express-docker</strong> folder:</p><pre>express-docker<br>├── package-lock.json<br>├── package.json<br>└── src<br>    ├── app.js<br>    ├── controllers<br>    │   └── sales.controller.js<br>    ├── database<br>    │   └── sales.sql<br>    ├── models<br>    │   └── sale.js<br>    ├── routes<br>    │   └── sales.routes.js<br>    └── util<br>        └── database.util.js</pre><h4>Step 4: Implementing Controller Functions</h4><p>Add the controller functions provided to <strong>src/controllers/sales.controller.js</strong>. These functions include <strong>getAllSales</strong>, <strong>getSaleById</strong>, and <strong>createSale</strong>.</p><pre>import Sale from &#39;../models/sale.js&#39;;<br><br>export const getAllSales = async (req, res) =&gt; {<br>    try {<br>        Sale.findAll().then(sales =&gt; {<br>            res.status(200).json({<br>                data: sales<br>            });<br>        });<br>    }<br>    catch (err) {<br>        res.status(500).json({ error: err.message });<br>    }<br>};<br>export const getSaleById = async (req, res) =&gt; {<br>    try {<br>        const id = req.params.id;<br>        Sale.findByPk(id).then(sale =&gt; {<br>            if (sale) {<br>                res.status(200).json({<br>                    data: sale<br>                });<br>            } else {<br>                res.status(404).json({<br>                    message: &#39;Sale not found&#39;<br>                });<br>            }<br>        });<br>    } catch (err) {<br>        res.status(500).json({ error: err.message });<br>    }<br>};<br>export const createSale = async (req, res) =&gt; {<br>    try {<br>        const { customer, product, price, address } = req.body;<br>        if (!customer || !product || !price || !address) {<br>            return res.status(400).json({ message: &#39;All fields are required&#39; });<br>        }<br>        const sale = await Sale.create({ customer, product, price, address });<br>        res.status(201).json({<br>            data: sale<br>        });<br>        <br>    }<br>    catch (err) {<br>        res.status(500).json({ error: err.message });<br>    }<br>};</pre><h4>Step 5: Define the Database Model</h4><p>In <strong>src/models/sale.js</strong>, define the Sequelize model for your <strong>sales</strong> table, and include functionality to sync the model with your database.</p><pre>import { Sequelize } from &quot;sequelize&quot;;<br>import { db } from &#39;../util/database.util.js&#39;<br><br>const Sale = db.define(&#39;sales&#39;, {<br>    id: {<br>        type: Sequelize.INTEGER,<br>        autoIncrement: true,<br>        allowNull: false,<br>        primaryKey: true<br>    },<br>    customer: {<br>        type: Sequelize.STRING,<br>        allowNull: false<br>    },<br>    product: {<br>        type: Sequelize.STRING,<br>        allowNull: false<br>    },<br>    price: {<br>        type: Sequelize.FLOAT,<br>        allowNull: false<br>    },<br>    address: {<br>        type: Sequelize.STRING,<br>        allowNull: false<br>    },<br>    createdAt: {<br>        type: Sequelize.DATE,<br>        allowNull: false,<br>        field: &#39;createdat&#39;<br>    },<br>    updatedAt: {<br>        type: Sequelize.DATE,<br>        allowNull: false,<br>        field: &#39;updatedat&#39;<br>    }<br>},{<br>    underscored: true,<br>});<br>db.sync().then(() =&gt; {<br>    console.log(&#39;Database &amp; tables created!&#39;);<br>}).catch(err =&gt; {<br>    console.log(err);<br>});<br>export default Sale;</pre><h4>Step 6: Setting Up Routes</h4><p>In <strong>src/routes/sales.routes.js</strong>, set up the routes to handle requests to your sales API endpoints using the controller functions.</p><pre>import express from &#39;express&#39;;<br>import { getAllSales, getSaleById, createSale } from &#39;../controllers/sales.controller.js&#39;;<br><br>const router = express.Router();<br>router.get(&#39;/&#39;, getAllSales);<br>router.get(&#39;/:id&#39;, getSaleById);<br>router.post(&#39;/&#39;, createSale);<br>export default router;</pre><h4>Step 7: Initializing the Express Application</h4><p>Create an Express server in <strong>src/app.js</strong>, apply middleware, and set up your routes.</p><pre>import express from &#39;express&#39;;<br>import bodyParser from &#39;body-parser&#39;;<br>import salesRouter from &#39;./routes/sales.routes.js&#39;;<br><br>const app = express();<br>app.use(bodyParser.json());<br>app.use((req, res, next) =&gt; {<br>  res.setHeader(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>  res.setHeader(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, PUT, DELETE&#39;);<br>  next();<br>});<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.json({ message: &#39;API ready to receive requests! 🚀&#39; });<br>});<br>app.use(&#39;/api/sales&#39;, salesRouter);<br>const PORT = process.env.APP_PORT;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port &lt;http://localhost&gt;:${PORT}`);<br>});<br>export default app;</pre><h4>Step 8: Setting Up Database Utilities</h4><p>In <strong>src/util/database.util.js</strong>, configure the Sequelize instance to connect to your PostgreSQL database using environment variables.</p><pre>import { Sequelize } from &quot;sequelize&quot;;<br><br>export const db = new Sequelize(<br>    process.env.POSTGRES_DB,<br>    process.env.POSTGRES_USER,<br>    process.env.POSTGRES_PASSWORD,<br>    {<br>        host: process.env.DB_HOST,<br>        port: process.env.DB_PORT,<br>        dialect: &#39;postgres&#39;,<br>    }<br>);</pre><h4>Step 9: Creating the SQL Database</h4><p>Utilize the <strong>src/database/sales.sql</strong> file to create and populate your <strong>sales</strong> table with initial data.</p><pre>CREATE TABLE sales (<br>  id SERIAL PRIMARY KEY,<br>  customer VARCHAR(255) NOT NULL,<br>  product VARCHAR(255) NOT NULL,<br>  price DECIMAL(10, 2) NOT NULL,<br>  address TEXT<br>);<br><br>INSERT INTO sales (customer, product, price, address) VALUES<br>(&#39;John Doe&#39;, &#39;Laptop&#39;, 999.99, &#39;123 Main St, Anytown, USA&#39;),<br>(&#39;Jane Smith&#39;, &#39;Smartphone&#39;, 699.99, &#39;456 Elm St, Anytown, USA&#39;),<br>(&#39;Alice Johnson&#39;, &#39;Headphones&#39;, 59.99, &#39;789 Maple St, Anytown, USA&#39;),<br>(&#39;Bob Brown&#39;, &#39;Camera&#39;, 349.95, &#39;321 Oak St, Anytown, USA&#39;),<br>(&#39;Charlie Black&#39;, &#39;Smartwatch&#39;, 199.99, &#39;654 Pine St, Anytown, USA&#39;),<br>(&#39;Diana Green&#39;, &#39;Tablet&#39;, 499.99, &#39;987 Cedar St, Anytown, USA&#39;),<br>(&#39;Ethan Grey&#39;, &#39;Gaming Console&#39;, 299.99, &#39;159 Birch St, Anytown, USA&#39;),<br>(&#39;Fiona White&#39;, &#39;E-reader&#39;, 129.99, &#39;246 Alder St, Anytown, USA&#39;),<br>(&#39;George Yellow&#39;, &#39;Bluetooth Speaker&#39;, 89.99, &#39;135 Spruce St, Anytown, USA&#39;),<br>(&#39;Hannah Purple&#39;, &#39;Laptop Stand&#39;, 39.99, &#39;864 Willow St, Anytown, USA&#39;),<br>(&#39;Ian Teal&#39;, &#39;Monitor&#39;, 199.99, &#39;975 Aspen St, Anytown, USA&#39;),<br>(&#39;Jenny Orange&#39;, &#39;Mouse&#39;, 29.99, &#39;321 Poplar St, Anytown, USA&#39;),<br>(&#39;Kyle Blue&#39;, &#39;Keyboard&#39;, 79.99, &#39;213 Cherry St, Anytown, USA&#39;),<br>(&#39;Laura Pink&#39;, &#39;Webcam&#39;, 49.99, &#39;456 Peach St, Anytown, USA&#39;),<br>(&#39;Mike Red&#39;, &#39;External Hard Drive&#39;, 99.99, &#39;789 Plum St, Anytown, USA&#39;)</pre><h4>Step 10: Updating package.json File</h4><p>To ensure that our application starts correctly and recognizes ES module syntax, we need to update the <strong>package.json</strong> file with some additional properties and a start script. This will also facilitate the usage of environment variables from a <strong>.env</strong> file when starting the application.</p><p>Here’s how to update your <strong>package.json</strong> file:</p><ol><li>Open the <strong>package.json</strong> file in your text editor.</li><li>Add the <strong>&quot;main&quot;: &quot;src/app.js&quot;</strong> property to specify the entry point of the application.</li><li>Add the <strong>&quot;type&quot;: &quot;module&quot;</strong> property to enable ES module syntax, which allows you to use <strong>import</strong> and <strong>export</strong> statements.</li><li>Under the <strong>&quot;scripts&quot;</strong> object, add a <strong>&quot;start&quot;</strong> script to start the application with the environment variables loaded from the <strong>.env</strong> file.</li></ol><p>After the update, your <strong>package.json</strong> file should look like this:</p><pre>{<br>  &quot;name&quot;: &quot;express-docker&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A Restful API with Node.js, Express and Docker&quot;,<br>  &quot;main&quot;: &quot;src/app.js&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \\&quot;Error: no test specified\\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node -r dotenv/config src/app.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;^1.20.2&quot;,<br>    &quot;express&quot;: &quot;^4.18.2&quot;,<br>    &quot;pg&quot;: &quot;^8.11.3&quot;,<br>    &quot;sequelize&quot;: &quot;^6.35.2&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;dotenv&quot;: &quot;^16.3.2&quot;<br>  }<br>}</pre><h4>Optional: Cloning the Project from GitHub</h4><p>If you want to skip the manual setup process, you can clone the pre-configured project from my GitHub repository:</p><pre>git clone https://github.com/hendurhance/express-dockerize.git</pre><p>This completes the setup for our Node.js API, we’re now ready to move on to the Dockerization process.</p><p><a href="https://github.com/hendurhance/express-dockerize">hendurhance/express-dockerize</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NWRtlBwgyjV5UHkH" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Creating a Dockerfile for your Node.js API</h3><p>In the spirit of “shipping software” through containerization, as mentioned in the introduction, we now setting the stage for Dockerizing our Node.js app. This process begins by establishing two key components: a <strong>Dockerfile</strong> and a <strong>docker-compose.yml</strong> file. Together, they will define the environment for our application and manage the orchestration of our services.</p><h4>The docker-compose.yml File</h4><p>Let’s start by creating a <strong>docker-compose.yml</strong> file. Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application&#39;s services, making it an ideal choice for local development and testing. Here&#39;s the <strong>docker-compose.yml</strong> content:</p><pre>version: &#39;3.8&#39;<br>services:<br>  app:<br>    build: .<br>    ports:<br>      - &#39;4000:4000&#39;<br>    environment:<br>      - APP_PORT=${APP_PORT}<br>      - POSTGRES_DB=${POSTGRES_DB}<br>      - POSTGRES_USER=${POSTGRES_USER}<br>      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}<br>      - DB_HOST=${DB_HOST}<br>      - DB_PORT=5432  # Use the default PostgreSQL port inside the Docker network<br>    depends_on:<br>      - db<br>  db:<br>    image: postgres:13<br>    environment:<br>      - POSTGRES_DB=${POSTGRES_DB}<br>      - POSTGRES_USER=${POSTGRES_USER}<br>      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}<br>    volumes:<br>      - pgdata:/var/lib/postgresql/data<br>      - ./src/database:/docker-entrypoint-initdb.d<br>    ports:<br>      - &#39;5434:5432&#39;  # Map the default PostgreSQL port to a different port on the host machine<br>volumes:<br>  pgdata:</pre><p>In this file:</p><ul><li>We define two services: <strong>app</strong> (our Node.js API) and <strong>db</strong> (our PostgreSQL database).</li><li>The <strong>app</strong> service is built from the Dockerfile in the current directory (<strong>.</strong>).</li><li>We map the local port <strong>4000</strong> to the Docker container&#39;s port <strong>4000</strong>.</li><li>We use environment variables to configure our application, pulling these from a <strong>.env</strong> file.</li><li>The <strong>db</strong> service uses the <strong>postgres:13</strong> image and sets up a persistent volume for the database data.</li></ul><h4>The Dockerfile</h4><p>Next, we create the <strong>Dockerfile</strong>, which instructs Docker on how to build our image:</p><pre># Use the official Node.js 16 image as a parent image<br>FROM node:16<br># Set the working directory<br>WORKDIR /usr/src/app<br># Copy package.json and package-lock.json to the working directory<br>COPY package*.json ./<br># Install node modules<br>RUN npm install<br># Copy the rest of your app&#39;s source code from your host to your image filesystem.<br>COPY . .<br># Your app binds to port 3000 so you&#39;ll use the EXPOSE instruction to have it mapped by the docker daemon<br>EXPOSE 3000<br># Define the command to run your app using CMD which defines your runtime<br>CMD [ &quot;npm&quot;, &quot;start&quot; ]</pre><p>In the <strong>Dockerfile</strong>, we:</p><ul><li>Start with a Node.js 16 base image.</li><li>Set the working directory inside the image to <strong>/usr/src/app</strong>.</li><li>Copy the <strong>package.json</strong> and <strong>package-lock.json</strong> files and install dependencies.</li><li>Copy the rest of the source code into the image.</li><li>Expose port <strong>3000</strong> and set the default command to start the app.</li></ul><h4>The .dockerignore File</h4><p>To avoid unnecessary files being sent to the Docker daemon, we create a <strong>.dockerignore</strong> file:</p><pre>node_modules<br>npm-debug.log<br>Dockerfile<br>.dockerignore<br>.git<br>.gitignore</pre><p>This file ensures that our local <strong>node_modules</strong> folder, log files, and version control directories are not copied into our Docker image, thus keeping it clean and lightweight.</p><h3>The .env File</h3><p>Lastly, we’ll add a <strong>.env</strong> file at the root of the project:</p><pre>APP_PORT=4000<br>POSTGRES_DB=postgres<br>POSTGRES_USER=postgres<br>POSTGRES_PASSWORD=postgres<br>DB_HOST=db<br>DB_PORT=5432  # Use the default PostgreSQL port<br>NODE_ENV=development</pre><p>This file will supply the environment variables necessary for our services. By having a <strong>.env</strong> file, we can easily change our environment configurations without modifying the code or the Docker setup.</p><h4>Starting and Stopping Your Docker Environment</h4><p>Once your <strong>.env</strong> file is in place and you&#39;ve configured your <strong>Dockerfile</strong> and <strong>docker-compose.yml</strong>, you&#39;re ready to bring your Dockerized Node.js API to life. To start your application and its associated services, you will use the following command:</p><pre>docker-compose up --build -d</pre><p>This command will:</p><ul><li>Build the images for the services defined in your <strong>docker-compose.yml</strong> file if they don&#39;t already exist (<strong>-build</strong>).</li><li>Start the containers in detached mode (<strong>d</strong>), allowing them to run in the background.</li></ul><p>After executing this command, Docker Compose will start your Node.js application container along with the PostgreSQL database container, as per your configuration. You can then navigate to <strong>http://localhost:4000</strong> in your browser to access your API.</p><p>When you’re done and you wish to stop all the services, you can bring down the entire setup gracefully using:</p><pre>docker-compose down</pre><p>This command will:</p><ul><li>Stop all the running containers that were started with <strong>docker-compose up</strong>.</li><li>Remove the stopped containers as well as any networks that were created.</li></ul><p>By using these commands in your workflow, you can spin up and tear down your development environments, ensuring a smooth and efficient development process. This level of control is another example of how Docker simplifies the management of development environments, reinforcing best practices and reducing potential inconsistencies across different development stages and team members’ machines.</p><p>By following these steps, we’ve now defined the Docker environment for your Node.js API. This setup illustrates the power of Docker in creating consistent and isolated development environments, and how it helps teams avoid “It works on my machine” problems by ensuring that applications run the same way, everywhere.</p><h3>Conclusion</h3><p>As we conclude, we’ve delved into establishing a Dockerized environment for Node.js API development, offering a practical guide from setup to execution. We started with a basic Node.js API and enhanced it with Docker’s containerization, ensuring consistent deployment on any system. Docker Compose further enabled us to define service dependencies, creating a synchronized environment. No matter where you are in your development journey, whether you’re a solo developer or part of a larger team, this article equipped you with the knowledge to adopt Docker and emphasize its role in modern software development for achieving stability and scalability. Containerization is more than a technique; it’s a transformative approach to building software that stands resilient while scaling. As developers, are we ready to embrace this shift and see how it shapes the future of our applications?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e4c22cf464" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-create-a-dockerized-environment-for-developing-and-testing-node-js-apis-b9e4c22cf464">How to Create a Dockerized Environment for Developing and Testing Node.js APIs</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2023 Unwrapped: A Year in Review]]></title>
            <link>https://medium.com/@hendurhance/2023-unwrapped-a-year-in-review-6fc018239ec1?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc018239ec1</guid>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[year-in-review]]></category>
            <category><![CDATA[introspection]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[2023]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 22:35:26 GMT</pubDate>
            <atom:updated>2024-01-02T05:52:19.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyAjntFjYac2ZNT_yJHKMg.jpeg" /><figcaption>Photo by <a href="https://medium.com/u/ea43bc51c3f7">Endurance, the Martian</a> of Third Mainland Bridge at UNILAG</figcaption></figure><p>2023, huh? It still feels like just a few days went by since I penned down my 2022 end-of-year review, titling it “From a Dreadful 2022 to a Promising 2023” (<a href="https://medium.com/@hendurhance/from-a-dreadful-2022-to-a-promising-2023-ecfe3cab2f96">link</a>). So, here’s to me — cheers 🥂, writing my year-end review for the second time. This helps me put this year into perspective, hoping that I can look back and be proud of how far I’ve come.</p><p>If I had to sum up this year in two words, I’d say ‘Stepping Stone.’ Do I truly believe that? Absolutely. Am I satisfied? Hell no! As someone intensely focused on their career and driven by results, I wouldn’t label this as one of my best years, nor would I call it one of my worst.</p><p>I vividly remember setting my goals early last year. Looking back, I did achieve many of them. However, the year took an unexpected turn. In May, close to a year after launching my startup with the goal of creating “a one-stop solution for creators and SMEs to expand their brand outreach”, my co-founder and I decided to ‘close down shop.’ Despite months of hard work and significant financial investment (we ended up broke), the venture proved unsuccessful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jDSXJ_kKNo6DdoGpOvmVQ.jpeg" /><figcaption>Photo by <a href="https://medium.com/u/ea43bc51c3f7">Endurance, the Martian</a> of Senate Building, UNILAG</figcaption></figure><p>Reflecting on my last year’s review, where I mentioned it was my third attempt at building a startup, I still consider it a win. The experience taught me valuable lessons that I’ll carry into my next startup. The first quarter was focused on building products, not just for my startup but for others as well. By mid Q2, I found myself applying for jobs. The job market lived up to its tough reputation — I sent out hundreds of applications, completed numerous technical assessments, reached the final stages, and received a few offers (some rejected, others rescinded due to hybrid work constraints).</p><p>I know you might be puzzled — rejecting job offers in a tough market? Yes, I did. I believe that, at this stage in my career, working for larger and more diverse companies is essential for my growth as an engineer. Confucius’ words, ‘If You’re the Smartest Person in the Room, You’re In the Wrong Room,’ resonate with me. I want mentorship and a challenging environment that these companies can’t offer all due respect to them.</p><p>Towards the end of Q2, I faced a setback, losing a role in the final round with a Croatian Fintech company. It affected my confidence for the rest of the year, plunging me into a state of depression during my second-semester exams.</p><p>But, as the meme goes, ‘never back down, never what ??? never give up!!!’ Went back to the root, and started relearning system designs and architecture, design patterns, and DSA. I delved into new technologies, exploring Nest.js with TypeScript, dabbling in AI, and improving my SQL skills.</p><p>Early in Q3, I took a social media detox, went MIA on all platforms, and secured a short contract role to build a microservice for a delivery company using Nest.js. Resuming social media activity in late Q4 coincided with the start of the new semester. Juggling a career and academics proved challenging, but amidst the losses, spending quality time with family and friends, and embracing solitude to recharge my social battery, brought some balance.</p><p>As 2023 draws to a close, let’s revisit some of the goals I set in my 2022 end-of-year review:</p><ul><li>Learn Django: I mean I read the docs a lot and built a small app with it, but I will not count that as <strong>learn</strong></li><li>Improve on Typescript</li><li>Swift/Flutter: I later decided I am not learning mobile, it’s backend engineering till whenever</li><li>Relearn SQL Scripting</li><li>Improving on my Cloud Services skills</li></ul><p>There are also goals I had for myself which I did achieve, started technical writing with my most performing articles being:</p><ul><li><a href="https://medium.com/@hendurhance/how-to-set-up-m2-macbook-for-software-development-4a5e20a7866a?source=user_profile---------10----------------------------"><strong>How to set up M2 MacBook for Software Development</strong></a></li><li><a href="https://medium.com/@hendurhance/how-obfuscation-works-in-software-development-7f52edfff520?source=user_profile---------8----------------------------"><strong>How Obfuscation Works in Software Development</strong></a></li><li><a href="https://medium.com/@hendurhance/how-to-build-a-weighted-round-robin-load-balancer-in-node-js-23f3f0364860?source=user_profile---------0----------------------------"><strong>How to Build a Weighted Round Robin Load Balancer in Node.js</strong></a></li></ul><p>which amassed thousands of views. I had planned on publishing an article every month, and in the early stages, I was indeed published 2–3 articles every month. However, I became lazy as time went by.</p><p>Another goal of mine that I achieved was contributing to open source. It was a fun ride, to be honest. From contributing to packages used by tens of thousands of developers around the globe to creating packages used by thousands of developers and developing learning resources that have garnered over 700+ stars on GitHub from people around the world. To highlight a few of my personal projects, open-source packages, and learning resources I built this year:</p><ul><li><a href="https://github.com/hendurhance/ui-ux">UI/UX Learning Resource</a>: I underwent a rewrite of the learning resource I authored in 2021, making it more in-depth and current.</li><li><a href="https://github.com/amplifiedhq/countries-atlas">CountryAtlas</a>: I collaborated with my friend <a href="https://github.com/classyrazy">Razaq</a> to build an NPM package around Q3 for country data, covering aspects like code, currency, flags, languages, etc.</li><li><a href="https://github.com/hendurhance/bazaar">Bazaar</a>: I built a complete auction system software from the ground up, dedicating the entire Q4 to the project. It was an endeavor where I learned a lot and enhanced my documentation skills.</li></ul><p>Some other projects, while not making the top 3 list, can be found in my <a href="https://github.com/hendurhance">GitHub profile.</a>.</p><p>I know some of you are reading this article and thinking, ‘Endurance, there are still some goals missing.’ Yeah, there are! I’ve been called a <em>weirdo</em> a couple of times because ‘I write but I do not read.’ Well, this year marked a change; I started reading, mainly self-help books. The books I’ve read include:</p><ul><li>‘Getting to Yes: Negotiating Agreement Without Giving In’ by Roger Fisher, William Ury, and Bruce Patton</li><li>‘The Art and Business of Online Writing: How to Beat the Game’ by Nicolas Cole</li><li>‘The Art &amp; Business Of Ghostwriting’ by Nicolas Cole</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFpTYbO_x3ZWMfQthAKzOQ.jpeg" /><figcaption>Photo by <a href="https://medium.com/u/ea43bc51c3f7">Endurance, the Martian</a> Faculty of Science, UNILAG</figcaption></figure><p>As we enter a new year, I’ve set fresh goals for 2024:</p><ul><li>Read a minimum of 5 books (fiction and non-fiction).</li><li>Learn Django.</li><li>Enhance DSA, System Design &amp; System Architecture skills.</li><li>Write over 25 articles and secure my first writing gig.</li><li>Improve Cloud Services proficiency (Azure, GCP, etc.).</li><li>Academic improvement.</li><li>Become a student ambassador for some reputable organizations.</li></ul><p>Looking back, 2023 served as a stepping stone. In 2024, it’s a no-nonsense approach — either go harder or go home. A special shout-out to my friends; naming everyone would turn this article into a 3000-word piece.</p><p>In the words of <a href="https://x.hashnode.dev/2023-year-in-review-hacksultan-clqtavirv000a08jq5b7ld5w5">hackSultan</a>:</p><blockquote><em>If you don’t set your own limitations, failure will set it for you. We thank God for last year, we triple our hustle this year. E go be ✌️.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc018239ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Weighted Round Robin Load Balancer in Node.js]]></title>
            <link>https://medium.com/@hendurhance/how-to-build-a-weighted-round-robin-load-balancer-in-node-js-23f3f0364860?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f3f0364860</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 09:27:06 GMT</pubDate>
            <atom:updated>2023-12-26T11:00:02.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3tQ7ZFOuXi0OGtP_" /><figcaption>Photo by <a href="https://unsplash.com/@jordanharrison?utm_source=medium&amp;utm_medium=referral">Jordan Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of distributed systems, load balancing is a key approach to solving problems. The first sentence seems yabba dabba doo, right? Let me take it down a notch. Distributed systems are groups of <strong>networked</strong> computers that share a common goal to carry out tasks according to <a href="https://en.wikipedia.org/wiki/Distributed_computing">Wikipedia</a>. Now, let’s imagine you find yourself in a large-sized store, and you’re stuck in a never-ending cashier line, each of the cashiers is responsible for scanning items you bought and mediating the payment process. Some operate with lightning speed, while others struggle to keep pace. In the world of distributed systems, each cashier checkpoint resembles a server collectively working toward a common goal.</p><p>Curious about where load balancing fits into this scenario? Picture an exceptionally skilled cashier manager who strategically assigns tasks to available cashiers to streamline the checkout process. Similarly, load balancing optimally distributes incoming tasks among servers in a distributed system. This dynamic process ensures the efficient utilization of resources, prevents bottlenecks, and ultimately enhances the system’s performance. In this article, we’ll delve into how we can build our very own load balancer in Node.js.</p><p>My implementation of building a Weighted Round Robin Load Balancer in Node.js</p><p><a href="https://github.com/hendurhance/express-balancify">GitHub - hendurhance/express-balancify: ExpressBalancify is a project showcasing the implementation of a load balancer using Express.js with a Round Robin algorithm for efficient traffic distribution across multiple servers.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PJGclxBJHEsefET_" /><figcaption>Photo by <a href="https://unsplash.com/@impatrickt?utm_source=medium&amp;utm_medium=referral">Patrick Tomasso</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Opt for a Distributed System? And Why Node.js?</h3><p>As your application gains popularity, the major challenge is managing the surge in traffic. The joy of a rapidly growing user base can quickly turn into dismay as server crashes and downtime affect your system, undermining its reliability. This is precisely where distributed systems step in, it distributes high traffic across various networks. In building these distributed systems and load balancers, Node.js emerges as a favored choice. The unique appeal of Node.js lies in its event-driven, non-blocking I/O model. This architecture enables it to efficiently handle a large number of concurrent connections, a critical feature for robust load balancing. Moreover, Node.js boasts an extensive ecosystem of libraries and frameworks that streamline the process of building load balancers. In the next section, we will explore the key components and steps to build a weighted round-robin load balancer in Node.js.</p><h3>Project Setup</h3><p>To initialize this project we need to ensure our development environment is properly set up. Here’s a quick checklist of what you’ll need to download and install:</p><ul><li><strong>Node.js and npm (Node Package Manager):</strong> These are essential for running JavaScript applications on your machine. You can download and install them from the official <a href="https://nodejs.org/en">Node.js</a> website.</li><li><strong>npx:</strong> This is a package runner tool that comes with npm. If you have npm installed (which comes with Node.js), you should already have npx. However, it’s always a good idea to double-check by running npx -v in your terminal.</li><li><strong>pm2 (Process Manager 2):</strong> We’ll use pm2 to manage our Node.js processes effectively. You can install it globally by running the following command</li></ul><pre>npm install -g pm2</pre><p>With these tools in place, let’s start setting up our project:</p><ol><li><strong>Create a New Folder:</strong> Begin by creating a new folder for your project. Open your terminal, navigate to the directory where you want to create the project and run the following command:</li></ol><pre>mkdir weighted-round-robin-load-balancer</pre><p>Move into the newly created directory:</p><pre>cd weighted-round-robin-load-balancer</pre><p>2.<strong> Initialize the Project:</strong> Run the following command to initiate a new Node.js project:</p><pre>npm init -y</pre><p>This will create a <strong>package.json</strong> file with default values. Feel free to modify the details according to your preferences when prompted.</p><p>The initial setup is complete! In the next section, we’ll start installing the necessary dependencies and building our Weighted Round Robin Load Balancer.</p><h3><strong>Dependencies Installation</strong></h3><p>Now that we’ve set up the project directory, the next step is to install the necessary dependencies. at will help us build our Weighted Round Robin Load Balancer in Node.js.These are the libraries</p><ul><li><strong>Express:</strong> The first and foremost dependency is Express, a fast, unopinionated, minimalist web framework for Node.js. Express will be the backbone of our load balancer, handling HTTP requests and routing them to the appropriate servers. To install Express, run the following command in your terminal:</li></ul><pre>npm install express</pre><ul><li><strong>http-proxy-middleware:</strong> Next, we need <strong>http-proxy-middleware</strong>, a powerful HTTP proxy middleware for Express. This will facilitate proxying requests to the selected servers based on the Weighted Round Robin algorithm. Install http-proxy-middleware with the following command:</li></ul><pre>npm install http-proxy-middleware</pre><ul><li><strong>axios:</strong> For making HTTP requests to the selected server, we’ll use axios, a popular promise-based HTTP client for the browser and Node.js. Install axios with:</li></ul><pre>npm install axios</pre><ul><li><strong>csvtojson:</strong> csvtojson is an npm package we will use to parse CSV to JSON when we need to simulate a database. To install use the command below:</li></ul><pre>npm install csvtojson</pre><ul><li><strong>csv-writer:</strong> We want to log the details of each request, including the timestamp, IP address, server port, and original URL. <strong>csv-writer</strong> will help us write this information to a CSV file.</li></ul><pre>npm install csv-writer</pre><ul><li><strong>Loadtest:</strong> Loadtest is a powerful and straightforward tool for testing the performance of your web applications under heavy load. It allows us to simulate multiple users hitting our load balancer simultaneously. Install load test as a dev dependency:</li></ul><pre>npm install --save-dev loadtest</pre><ul><li>Alternatively, for your convenience, you can install all the dependencies and dev tools in one go using the following command:</li></ul><pre>npm install express http-proxy-middleware axios csv-writer csvtojson loadtest --save</pre><h3><strong>Creating the Express Application</strong></h3><p>Begin by creating a new folder named <strong>src</strong> in the root directory of your project. This folder will contain all our source code. Inside the <strong>src</strong> folder, create a file named <strong>index.js</strong>. This file will serve as the entry point for our application.</p><pre>mkdir src <br>touch src/index.js</pre><p>Now, open <strong>src/index.js</strong> with your preferred text editor. We&#39;ll write a basic Express.js application to make sure everything is set up correctly.</p><h4><strong>Writing a Simple Express App</strong></h4><p>In <strong>src/index.js</strong>, add the following code to create a minimal Express application:</p><pre>import express from &#39;express&#39;;<br><br>const app = express();<br>const port = 8000;<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello, Weighted Round Robin Load Balancer!&#39;);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on http://localhost:${port}`);<br>});</pre><p>This code sets up a basic Express server that listens on port 8000 and responds with a “Hello, Weighted Round Robin Load Balancer!” message when you access the root URL.</p><h4><strong>Updating </strong><strong>package.json for ES6 Module Support</strong></h4><p>To enable ES6 module support, we need to make a few changes to our <strong>package.json</strong> file. Open <strong>package.json</strong> and modify it as follows:</p><pre>{<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;main&quot;: &quot;src/index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node src/index.js&quot;<br>  },<br>  // other configurations...<br>}</pre><p>We’ve set the <strong>&quot;type&quot;</strong> field to <strong>&quot;module&quot;</strong> to indicate that our project uses ES6 modules. Additionally, we updated the <strong>&quot;main&quot;</strong> field to point to our entry file (<strong>src/index.js</strong>) and added a <strong>&quot;start&quot;</strong> script to run our application using Node.js.</p><h3>Understanding the Need for Multiple Servers</h3><p>Now that we have an express project up and running, to distribute incoming requests effectively we will have to use multiple servers. To address this, we’ll be setting up not one but <strong>ten servers</strong> to handle incoming requests. This approach allows us to distribute the load across multiple servers, ensuring a more balanced and responsive system.</p><h4>Creating a Common.js File for Efficient Server Creation</h4><p>Now, you might be wondering, “Do I have to duplicate server creation logic for all ten servers?” The answer is no! We can enhance maintainability by consolidating the server creation code into a common file. Let’s create a <strong>common.js</strong> file in the <strong>src</strong> directory to encapsulate the logic for creating servers.</p><pre>touch src/common.js</pre><p>Open <strong>src/common.js</strong> in your text editor, and let&#39;s define a function that creates an Express server:</p><pre>import express from &quot;express&quot;;<br><br>function createServer(port) {<br>  const app = express();<br>  app.get(&quot;/&quot;, (req, res) =&gt; {<br>    res.json({<br>      server: `[Load Balancer] Server listening on port ${port}`,<br>      message: &quot;Welcome to the Load Balancer! Please use the /api endpoint to access the data.&quot;<br>    });<br>  });<br>  app.listen(port, () =&gt; {<br>    console.log(`Server listening on port ${port}`);<br>    console.log(`Process PID: ${process.pid}`);<br>  });<br>}<br>export { createServer };</pre><p>This <strong>createServer</strong> function takes a <strong>port</strong> as a parameter, creating an Express server that responds with the provided message when accessed.</p><h4>Creating Multiple Server Files</h4><p>Now that we have our <strong>common.js</strong> file ready to go, let&#39;s create individual server files that will use this common logic. Having separate files for each server not only keeps our code organized but also allows us to customize the behavior of each server.</p><h4>Generating Server Files</h4><p>Create ten server files in the <strong>src/servers</strong> directory, each representing a server in our load-balancing setup. Naming them <strong>1.js</strong>, <strong>2.js</strong>, and so on up to <strong>10.js</strong> will help us keep track.</p><pre>cd src<br>mkdir servers<br>cd servers<br>touch {1..10}.js</pre><p>Now, let’s open each of these files and set up our servers using the <strong>createServer</strong> function from our <strong>common.js</strong> file.</p><h4>Configuring Individual Servers</h4><p>Open each <strong>N.js</strong> file in your text editor and configure them as follows:</p><pre>// src/1.js (Replace &#39;1&#39; with the corresponding server number)<br>import { createServer } from &quot;../common.js&quot;;<br><br>const port = 5073; // Each server the 0 in 5073 changes<br>createServer(port);</pre><p>Repeat this process for the remaining <strong>N.js</strong> files, updating the <strong>port</strong> accordingly to 5073, 5173, 5273… 5973. By having separate server files, we can easily customize the behavior of each server, making our load-balancing setup more dynamic. In the next section, we&#39;ll explore the Weighted Round Robin algorithm, which will determine how incoming requests are distributed among these ten servers.</p><h3>Understanding the Weighted Round Robin Algorithm</h3><p>Before diving into the code implementation, let’s understand what the Weighted Round Robin algorithm is. This balancing strategy distributes incoming requests among servers based on their assigned weights. Servers with higher weights receive more requests than those with lower weights, providing a flexible way to allocate resources based on server capabilities.</p><h4>Real-World Analogy</h4><p>From our illustration earlier of a large-sized store with multiple cashiers, each excellent in handling different types of transactions. The store manager aims to efficiently distribute incoming customers among the cashiers based on their skill levels. In this scenario, the cashiers’ expertise levels act as the weights. A cashier with higher expertise (weight) manages a greater number of transactions. This parallels the Weighted Round Robin algorithm’s concept, where tasks (customers) are intelligently allocated based on the assigned weights. Now, let’s delve into the updated load balancer implementation, incorporating this real-world analogy.</p><h4>Updating the Load Balancer</h4><p>Open the <strong>src/index.js</strong> file and modify it as follows:</p><pre>import express from &#39;express&#39;;<br>import httpProxy from &#39;http-proxy-middleware&#39;;<br>import axios from &#39;axios&#39;;<br>import { createObjectCsvWriter } from &#39;csv-writer&#39;;<br><br>const serverConfigurations = [<br>  { port: 5073, weight: 2 },<br>  { port: 5173, weight: 1 },<br>  { port: 5273, weight: 2 },<br>  { port: 5373, weight: 1 },<br>  { port: 5473, weight: 2 },<br>  { port: 5573, weight: 1 },<br>  { port: 5673, weight: 2 },<br>  { port: 5773, weight: 1 },<br>  { port: 5873, weight: 2 },<br>  { port: 5973, weight: 1 },<br>];<br>const app = express();<br>const port = 8000;<br>// Create a CSV writer to log requests<br>const csvWriter = createObjectCsvWriter({<br>  path: &#39;request_logs.csv&#39;,<br>  header: [<br>    { id: &#39;timestamp&#39;, title: &#39;Timestamp&#39; },<br>    { id: &#39;ip&#39;, title: &#39;IP Address&#39; },<br>    { id: &#39;serverPort&#39;, title: &#39;Server Port&#39; },<br>    { id: &#39;originalUrl&#39;, title: &#39;Original URL&#39; },<br>  ],<br>});<br>// Middleware to randomly select a server using Weighted Round Robin algorithm<br>app.use((req, res, next) =&gt; {<br>  const selectedServer = selectServer(serverConfigurations);<br>  req.selectedServer = selectedServer;<br>  // Log the request information to CSV<br>  const logData = {<br>    timestamp: new Date().toISOString(),<br>    ip: req.ip,<br>    serverPort: selectedServer ? selectedServer.port : &#39;N/A&#39;,<br>    originalUrl: req.originalUrl,<br>  };<br>  csvWriter.writeRecords([logData]);<br>  if (selectedServer) {<br>    proxyRequest(req, res);<br>  } else {<br>    res.status(503).send(&#39;Service Unavailable&#39;);<br>  }<br>});<br>// Proxy middleware for the selected server<br>const selectedServerProxy = httpProxy.createProxyMiddleware({<br>  target: &#39;&lt;http://localhost&gt;&#39;, // Set the target to the base URL of your servers<br>  changeOrigin: true,<br>});<br>// Use the proxy middleware for all routes<br>app.use(&#39;/&#39;, selectedServerProxy);<br>app.listen(port, () =&gt; {<br>  console.log(`Load Balancer listening at &lt;http://localhost&gt;:${port}`);<br>});<br>// Function to select a server using Weighted Round Robin<br>function selectServer(serverConfigurations) {<br>  let currentWeightIndex = 0; <br>  while (true) {<br>    const totalWeight = serverConfigurations.reduce((acc, config) =&gt; acc + config.weight, 0);<br>    const randomNum = Math.floor(Math.random() * totalWeight);<br>    let weightSum = 0;<br>    for (let i = currentWeightIndex; i &lt; serverConfigurations.length; i++) {<br>      const config = serverConfigurations[i];<br>      weightSum += config.weight;<br>      if (randomNum &lt; weightSum) {<br>        currentWeightIndex = (i + 1) % serverConfigurations.length; // Update index for the next round<br>        return config;<br>      }<br>    }<br>    currentWeightIndex = 0;<br>  }<br>}<br>// Function to proxy the request to the selected server<br>function proxyRequest(req, res) {<br>  const selectedServer = req.selectedServer;<br>  const selectedPort = selectedServer.port;<br>  const originalUrl = req.originalUrl; // Store original URL<br>  axios.get(`http://localhost:${selectedPort}${originalUrl}`)<br>    .then((serverResponse) =&gt; {<br>      const responseData = serverResponse.data; // Get response data from server<br>      // Send response data to client<br>      res.send(responseData);<br>    })<br>    .catch((error) =&gt; {<br>      console.error(`Error forwarding request to server: ${error}`);<br>      res.status(500).send(&#39;Internal Server Error&#39;);<br>    });<br>}</pre><p>In this modified <strong>index.js</strong> code, we&#39;ve refined the Weighted Round Robin algorithm implementation for better clarity and efficiency. The core logic now resides in the <strong>selectServer</strong> function, ensuring a more organized approach to server selection. We&#39;ve introduced a <strong>currentWeightIndex</strong> variable to keep track of the last selected server&#39;s index, avoiding unnecessary iterations during subsequent requests. The algorithm now accurately distributes incoming requests among servers based on their specified weights, providing a balanced and weighted load distribution.</p><p>Additionally, error handling and fallback mechanisms have been enhanced. When no server is available (due to, for instance, temporary unavailability or high loads on all servers), the load balancer responds with a <strong>503 Service Unavailable</strong> status, indicating that the service is temporarily unable to process the request. This ensures a more resilient and user-friendly experience. The use of the <strong>httpProxy</strong> middleware remains pivotal, seamlessly forwarding requests to the selected server, while comprehensive logging <strong>csvWriter</strong> captures essential request details for future analysis.</p><h3>Imitating a Database: Using Kaggle’s CSV Dataset</h3><p>To emulate a practical scenario, we’ll simulate a database using a CSV file. You can download the required dataset from Kaggle <a href="https://www.kaggle.com/datasets/kyanyoga/sample-sales-data/">here</a>, and add it to the project directory under the <strong>data</strong> folder in the root directory. This dataset will act as our pseudo-database, enriching the experience of our load-balancing simulation. To adapt our load balancer to this new setup, we&#39;ll make adjustments to the <strong>common.js</strong> file and each server file. In <strong>common.js</strong>, we&#39;ll incorporate code that reads and processes data from the CSV file, ensuring our load balancer now interacts with this pseudo-database.</p><h4>Updating the Common.js</h4><p>Let’s enhance our <strong>common.js</strong> file to integrate the new dataset we&#39;ve acquired. Begin by creating a <strong>data</strong> folder in your project&#39;s root directory. Inside this folder, add the unzipped CSV file obtained from Kaggle and rename it to sample.csv. Now, let&#39;s update <strong>common.js</strong> to effectively incorporate this dataset.</p><pre>// common.js<br>import express from &quot;express&quot;;<br>import csv from &quot;csvtojson&quot;;<br><br>const itemsPerPage = 100;<br>function createServer(port, csvFilePath = &quot;data/sample.csv&quot;) {<br>  const app = express();<br>  app.get(&quot;/&quot;, (req, res) =&gt; {<br>    res.json({<br>      server: `[Load Balancer] Server listening on port ${port}`,<br>      message: &quot;Welcome to the Load Balancer! Please use the /api endpoint to access the data.&quot;<br>    });<br>  });<br>  app.get(&quot;/api&quot;, async (req, res) =&gt; {<br>    const page = parseInt(req.query.page, 10) || 1;<br>    console.log(`Page ${page} requested`);<br>    try {<br>      const csvRows = await csv({<br>        noheader: true,<br>        output: &quot;csv&quot;<br>      }).fromFile(csvFilePath);<br>      if (!csvRows || csvRows.length === 0) {<br>        return res.status(404).json({ error: &quot;CSV file is empty or not found.&quot; });<br>      }<br>      const headers = getHeaders(csvRows[0]);<br>      // Convert CSV rows to JSON format including headers<br>      const json = csvRows.slice(1).map((row) =&gt; {<br>        const item = {};<br>        for (let j = 0; j &lt; headers.length; j++) {<br>          item[headers[j].toLowerCase()] = row[j];<br>        }<br>        return item;<br>      });<br>      // Paginate the JSON array<br>      const startIndex = (page - 1) * itemsPerPage;<br>      const endIndex = startIndex + itemsPerPage;<br>      const paginatedJson = json.slice(startIndex, endIndex);<br>      res.setHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>      res.json({<br>        server: `[Load Balancer] Server listening on port ${port}`,<br>        page,<br>        itemsPerPage,<br>        total: json.length,<br>        totalPages: Math.ceil(json.length / itemsPerPage),<br>        data: paginatedJson<br>      });<br>    } catch (error) {<br>      console.error(&quot;Error reading CSV:&quot;, error);<br>      res.status(500).json({ error: &quot;Internal Server Error&quot; });<br>    }<br>  });<br>  app.listen(port, () =&gt; {<br>    console.log(`Server listening on port ${port}`);<br>    console.log(`Process PID: ${process.pid}`);<br>  });<br>}<br>function getHeaders(firstRow) {<br>  // Check if the first row looks like valid identifiers<br>  return firstRow.map((header) =&gt; header.trim());<br>}<br>export { createServer };</pre><h4>Starting Servers</h4><p>Let’s optimize our development workflow by adding some helpful commands to our <strong>package.json</strong> file. Open the <strong>package.json</strong> and under the <strong>&quot;scripts&quot;</strong> section, include the following:</p><pre>&quot;scripts&quot;: {<br>  &quot;start:load-balancer&quot;: &quot;node src/index.js&quot;,<br>  &quot;start:server&quot;: &quot;pm2 start ./src/servers/1.js &amp;&amp; pm2 start ./src/servers/2.js &amp;&amp; pm2 start ./src/servers/3.js &amp;&amp; pm2 start ./src/servers/4.js &amp;&amp; pm2 start ./src/servers/5.js &amp;&amp; pm2 start ./src/servers/6.js &amp;&amp; pm2 start ./src/servers/7.js &amp;&amp; pm2 start ./src/servers/8.js &amp;&amp; pm2 start ./src/servers/9.js &amp;&amp; pm2 start ./src/servers/10.js&quot;<br> &quot;stop&quot;: &quot;pm2 stop all&quot;<br>},</pre><p>These commands will allow us to start our load balancer and multiple server instances easily. To get the servers and load balancer up and running, run:</p><pre>npm run start:server<br>npm run start:load-balancer</pre><h4>Testing Load Balancer Performance</h4><p>Now that we’ve set up our load balancer and servers, it’s time to put them to the test. We’ll be using the <strong>loadtest</strong> tool to simulate various scenarios and assess the load balancer&#39;s performance. First, ensure you have <strong>loadtest</strong> installed globally by running:</p><pre>npm install -g loadtest</pre><p>Now, add the following commands to your <strong>package.json</strong> under the <strong>&quot;scripts&quot;</strong> section:</p><pre>&quot;scripts&quot;: {<br>  &quot;test:load:health&quot;: &quot;npx loadtest -n 1200 -c 400 -k http://localhost:8000&quot;,<br>  &quot;test:load:api&quot;: &quot;npx loadtest -n 1200 -c 400 -k http://localhost:8000/api&quot;,<br>},</pre><p>These commands execute load tests with 1200 requests and a concurrency of 400, assessing the health endpoint (<strong>/</strong>) and the API endpoint (<strong>/api</strong>), respectively. To run the tests, open your terminal and execute:</p><pre>npm run test:load:health<br>npm run test:load:api</pre><h3>Decoding Load Test Results: Understanding the Numbers</h3><p>We subjected our weighted round-robin load balancer to two comprehensive load test scenarios, scrutinizing its performance under varying conditions. Let’s decipher the outcomes:</p><h4>Test Scenario 1: Health Endpoint Load Test</h4><p>Command Executed:</p><pre>npm run test:load:health</pre><p><strong>Overview:</strong></p><ul><li><strong>Max Requests:</strong> 1200</li><li><strong>Concurrent Clients:</strong> 1600</li><li><strong>Total Errors:</strong> 183</li><li><strong>Total Time:</strong> 0.835 seconds</li><li><strong>Mean Latency:</strong> 485.6 ms</li><li><strong>Effective Requests Per Second (rps):</strong> 1437</li></ul><p><strong>Latency Distribution:</strong></p><ul><li><strong>50% of Requests Served Within:</strong> 501 ms</li><li><strong>90% of Requests Served Within:</strong> 716 ms</li><li><strong>95% of Requests Served Within:</strong> 723 ms</li><li><strong>99% of Requests Served Within:</strong> 732 ms</li><li><strong>Longest Request:</strong> 733 ms</li></ul><p><strong>Analysis:</strong> The health endpoint load test showcased robust performance, with a majority of requests served within a remarkably short timeframe. Despite encountering 183 errors, the load balancer demonstrated resilience, maintaining an impressive effective request rate per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbp0bswFSOm99EzzsNrXSw.png" /><figcaption>Load Test for Health Check Route</figcaption></figure><h4>Test Scenario 2: API Endpoint Load Test</h4><p>Command Executed:</p><pre>npm run test:load:api</pre><p><strong>Overview:</strong></p><ul><li><strong>Max Requests:</strong> 1200</li><li><strong>Concurrent Clients:</strong> 1600</li><li><strong>Total Errors:</strong> 282</li><li><strong>Total Time:</strong> 9.053 seconds</li><li><strong>Mean Latency:</strong> 4857.9 ms</li><li><strong>Effective Requests Per Second (rps):</strong> 133</li></ul><p><strong>Latency Distribution:</strong></p><ul><li><strong>50% of Requests Served Within:</strong> 5806 ms</li><li><strong>90% of Requests Served Within:</strong> 8247 ms</li><li><strong>95% of Requests Served Within:</strong> 8557 ms</li><li><strong>99% of Requests Served Within:</strong> 8828 ms</li><li><strong>Longest Request:</strong> 8969 ms</li></ul><p><strong>Analysis:</strong> The API endpoint load test exhibited a higher mean latency, attributed to variations in the complexity of API requests. Despite encountering 282 errors, the load balancer sustained an effective request rate, showcasing its ability to handle demanding scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTQU6mUctmUImkLdZ2sq0w.png" /><figcaption>Load Test for Sales API Route</figcaption></figure><h3>Analyzing Request Log</h3><p>We’ve put our load balancer to the test, it’s time to analyze the numbers and unveil patterns from the data gathered from the request logs. Create a analyze.py file in the root of your directory then add the following Python script:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>csv_file = &#39;request_logs.csv&#39;<br>df = pd.read_csv(csv_file, parse_dates=[&#39;Timestamp&#39;])<br>total_requests = len(df)<br>failed_requests = df[df[&#39;Server Port&#39;] == &#39;N/A&#39;].shape[0]<br>requests_per_second = total_requests / (df[&#39;Timestamp&#39;].max() - df[&#39;Timestamp&#39;].min()).total_seconds()<br><br># Generate a bar chart with the distribution of responses between server ports<br>server_port_distribution = df[&#39;Server Port&#39;].value_counts()<br>server_port_distribution.plot(kind=&#39;bar&#39;, rot=0, color=&#39;skyblue&#39;)<br>plt.title(&#39;Distribution of Requests Between Server Ports&#39;)<br>plt.xlabel(&#39;Server Port&#39;)<br>plt.ylabel(&#39;Number of Requests&#39;)<br>plt.show()<br><br># Generate a bar chart with the highest amount of requests handled by each server<br>highest_requests_by_server = df.groupby(&#39;Server Port&#39;).size().plot(kind=&#39;bar&#39;, rot=0, color=&#39;lightcoral&#39;)<br>plt.title(&#39;Highest Amount of Requests Handled by Each Server&#39;)<br>plt.xlabel(&#39;Server Port&#39;)<br>plt.ylabel(&#39;Number of Requests&#39;)<br>plt.show()<br><br># Generate a pie chart showing the percentage distribution of requests between server ports<br>server_port_percentage = df[&#39;Server Port&#39;].value_counts() / total_requests * 100<br>server_port_percentage.plot(kind=&#39;pie&#39;, autopct=&#39;%1.1f%%&#39;, startangle=90, colors=[&#39;gold&#39;, &#39;lightgreen&#39;, &#39;lightcoral&#39;, &#39;lightskyblue&#39;, &#39;lightpink&#39;])<br>plt.title(&#39;Percentage Distribution of Requests Between Server Ports&#39;)<br>plt.axis(&#39;equal&#39;)<br>plt.show()</pre><p>To run this Python script use the following command:</p><pre>python analyze.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7dMBXy0BNrulQH6k14CBHA.png" /><figcaption>Bar chart representing the distribution of traffic between server ports</figcaption></figure><p>As we analyze the distribution of requests between server ports, a compelling pattern emerges. The ports 5673, 5073, 5873, 5472, and 5273, each with twice the weight compared to others, distinctly performed better. This supremacy is vividly seen in the bar chart, where these high-weight ports handle almost twice the number of requests as their counterparts with lower weights (5973, 5373, 5773, 5573, and 5173). The impact of the weighted round-robin algorithm becomes noticeable, demonstrating its effectiveness in optimizing resource utilization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2IS4rRKDuPZhSBmkbh0Uaw.png" /><figcaption>Bar chart representing the highest amount of requests handled by each server</figcaption></figure><p>Diving deeper into the server performance, the chart illustrating the highest number of requests handled by each server affirms our observations. Ports 5073 and 5273, boasting higher weights, consistently outshining the others, and registering over a thousand requests at their peak. Meanwhile, ports 5173, 5373, and 5573, with lower weights, exhibit a commendable but comparatively moderate performance, indicating a direct correlation between weight and processing capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AerjxhTgveHnZLMFu_TKFQ.png" /><figcaption>Pie Chart representing the distribution of traffic between server ports</figcaption></figure><p>This weighted orchestration is further corroborated by the pie chart, elucidating the percentage distribution of traffic among server ports. Ports 5673, 5073, and 5873 command significant slices, each claiming around 13.8% of the total requests. In contrast, ports 5173, 5373, and 5573 secure smaller but proportionate portions, affirming the calculated balance imparted by the weighted round-robin algorithm. This view substantiates the deliberate design choices in our load-balancing strategy, showcasing how weighting empowers certain servers to shoulder a more substantial share of the traffic, ensuring an optimized and resilient system.</p><h3>Conclusion</h3><p>As we conclude this article, we’ve discussed how to build our very own Weighted Round Robin Load Balancer in Node.js. We didn’t just dive into lines of code; we explained how load balancers work and their relationship to distributed systems. We began with the foundational understanding of distributed systems, where traffic management resembles a store’s checkout process with multiple cashiers. By applying the Weighted Round Robin algorithm, we effectively tuned our load balancer to distribute with precision, ensuring each server plays its unique role. This highlights the benefits of load balancing, including high availability, flexibility, scalability, and visibility. The article has showcased how our distributed systems architect solutions solve immediate challenges today and prepare us to scale products for millions of users</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f3f0364860" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Fans to Foes: The Reality of Stan and Cancel Culture]]></title>
            <link>https://medium.com/@hendurhance/from-fans-to-foes-the-reality-of-stan-and-cancel-culture-358483edd787?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/358483edd787</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[fandom]]></category>
            <category><![CDATA[celebrity]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 08:01:57 GMT</pubDate>
            <atom:updated>2023-12-05T08:01:57.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFZlAYSMpT9y5Y6eNv4o-A.png" /><figcaption>A split image or collage representing the contrast between extreme admiration (Stan Culture) and harsh judgment (Cancel Culture)</figcaption></figure><p>Reflecting on a sunny day in school a year ago, I vividly recall envisioning this article with a unique perspective. As I sat down to write, however, the words seemed to take on a life of their own, deviating from the carefully crafted narrative in my mind. Despite rewriting it twice since then, I find myself at a crossroads, wondering how to bring my original perspective into words. So, here we go — I hope to capture the essence I initially envisioned, but if not, I’m embracing the journey, and this piece will stand as it is. Whether anyone reads it or not, that’s a different tale altogether.</p><p>Speaking of the journey, social media has traversed a considerable distance from the famous ‘Poke’ on Facebook in the early 2000s to its current state. The content landscape has undergone a complete transformation, thanks to the emergence of new social media platforms such as TikTok and Instagram. The algorithms embedded within these platforms have the power to <em>catapult</em> anyone to fame, from the depths of obscurity to the heights of social media stardom. Yet, as long as humans exist, there will always be those who take things to extremes. This journey unfolds like a rollercoaster, riding the highs of obsessive fandoms and navigating the lows of online judgments.</p><p>I understand that not everyone understands the buzzwords ‘<strong>Stan and Cancel Culture.</strong>’ Picture this — you’re in a public bus on your way somewhere, scrolling through your timeline, and suddenly, you’re knee-deep in a heated discussion with someone you’ll probably never meet about the latest fan frenzy (stans) or someone being dragged for something offensive or an opinion that didn’t sit well with others (canceling).</p><p>According to <a href="https://www.dictionary.com/browse/stan-culture">Dictionary.com</a>:</p><blockquote><em>Stan culture is </em><strong>the behaviour or beliefs of an extreme fandom whose members fervently and blindly support their chosen celebrity or team, often demonizing or reviling anyone or anything opposed to, or not sufficiently devoted to, the object of their worship.</strong></blockquote><p>On the flip side, Cancel Culture, as per <a href="https://www.pewresearch.org/internet/2021/05/19/americans-and-cancel-culture-where-some-see-calls-for-accountability-others-see-censorship-punishment/">Pew Research</a>:</p><blockquote><em>Cancel culture is </em><strong>a movement to remove celebrity status or esteem from a person, place, or thing based on offensive behaviour or transgression.”</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ueg8xZIm9PPoa97G" /><figcaption>Photo by <a href="https://unsplash.com/@hannynaibaho?utm_source=medium&amp;utm_medium=referral">Hanny Naibaho</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Stan Culture: When Admiration Goes Full Stalker Mode</h3><p>I mean, we all have celebrities we look up to. I’ve admired a few for their exceptional skills. Juice WRLD, for instance, captured my attention with his ability to articulate profound thoughts in the form of song lyrics, and Paul Walker ignited my passion for cars.</p><p>Recently, at the <a href="https://www.devfestlagos.com/">DevFestLagos</a> conference, I attended, a speaker named <a href="https://twitter.com/tushgeek">TushGeek</a> dropped a truth bomb that resonated with me. He said, <strong><em>‘You can look up to anyone; you can make anyone your mentor, and they don’t have to know you.’</em></strong> It hit home — the idea that admiration knows no boundaries. You can appreciate someone for their expertise in a particular field, and it doesn’t matter if they’re aware of it or not.</p><p>But here’s where it gets interesting — Stan culture, born out of this genuine admiration, sometimes toes the line of infatuation. There’s a fine balance between admiring someone and veering into the realm of obsession. We’ve all seen fans take it to the extreme — creating shrines, crowdfunding cars and houses for their favourite celebrities, even when they are still struggling to make ends meet.</p><p>Now, as someone who frequently uses Twitter, I’ve had my front-row seat to witness stans doing the absolute most, from the dedicated BTS Army to the ever-passionate Swifties. It’s like entering a digital arena where admiration transforms into a full-blown spectacle. Stans don’t just admire; they often go full stalker mode, dissecting every tweet, decoding every Instagram story, and probably analyzing the pixels in the latest paparazzi shot. It’s an unwritten law in Stan Land — dare to question or criticize their beloved icon, and you’ll find yourself being <em>dragged in the mud</em>. These obsessive fans can unleash a barrage of tweets, and memes, and, in extreme cases, might even attempt to ‘cancel’ anyone who dares to speak against their ‘chosen one’. Some has even gone as far as finding them in their home. It’s an online battleground where the lines between passionate support and cyberbullying blur, and navigating through it is like tiptoeing across a minefield.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yWmQ05pokwVtRZti" /><figcaption>Photo by <a href="https://unsplash.com/@stereophototyp?utm_source=medium&amp;utm_medium=referral">Sara Kurfeß</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Cancel Culture: The Cyber Tribunal of Social Media</h3><p>Ah, the realm of cancel culture — a concept I wouldn’t even wish upon my enemies. Picture this: a mob descending upon you for a controversial opinion, your phone incessantly buzzing for hours, and with every passing hour, the storm intensifies. Your phone blowing up is the least of your concerns, getting judged by a jury of a thousand Twitter (can be any social media) users is when things feel like hell and your social status goes down the drain.</p><p>But is cancel culture a necessary evil? We’ve seen instances where celebrities seem to get away with anything, consequence-free. While cancel culture might appear extreme, I find myself leaning toward the belief that it’s somewhat needed. Fame often becomes a shield for some, giving them the audacity to break rules because they think they can. However, a mere recording, a snippet showing the world their misstep, and suddenly, their fame goes down the drain.</p><p>Now, I know what you’re thinking — does it have to go that far? I don’t have all the answers. People should be held accountable for what they put out into the world. We all make mistakes, and we should be allowed to change. Yet, the story takes a turn when individuals repeatedly make the same mistakes; at that point, they deserve whatever consequences come their way.</p><h3>From Fans to Foes</h3><p>In the world of stan and cancel culture, the transition from fan to foe is a perplexing journey. You might start by celebrating your favourite artist’s triumphs, creating memes, and forming bonds with fellow fans. But, oh, how swiftly the tide can turn. A celebrity’s single misstep, a controversial stance, and the alliances once solidified through admiration swiftly crumble. The dynamics of online communities undergo a dramatic upheaval, with fans-turned-foes expressing disillusionment and sometimes even hostility. It’s not merely a shift in perspective; it’s a testament to the volatile nature of digital allegiance, where the tide can turn with such speed that fans may find themselves on the opposite shore, questioning their once unwavering support.</p><h3>Addressing Common Questions</h3><ul><li><strong>Isn’t Cancel Culture just cyberbullying under a different name? </strong>As I said earlier in this piece, cancel culture shares similarities with cyberbullying, as it involves a mass call-out or attack on individuals for having done something controversial. However, the intent behind it may vary. While cyberbullying often aims to harm, cancel culture can also be a tool for accountability.</li><li><strong>Are Stan Culture and Cancel Culture ruining free speech? </strong>I mean they walk a fine line, but there is a difference between holding someone accountable for harmful actions and depriving someone of their free speech. Stan and Cancel Culture may spark debates, but it’s up to individuals to responsibly express their opinions while respecting diverse perspectives.</li><li><strong>Can someone bounce back after being canceled? </strong>Yes, individuals have the potential to recover from cancelation. But from what I’ve mostly witnessed, it is difficult for most due to its effect mentally. Genuine apologies, self-reflection, and positive actions can contribute to redemption. The online world may be quick to judge, but it’s not devoid of forgiveness.</li></ul><h3>Conclusion</h3><p>In the era of stan and cancel culture, it’s crucial to acknowledge the inherent risks beneath the surface. While born from admiration and a desire for accountability, these trends can quickly spiral into extremism. The fervent obsession of stans may lead to privacy invasions, while cancel culture, in its pursuit of justice, risks becoming a cyber tribunal without due process. Striking a balance is key — celebrate idols without crossing into unhealthy obsession, and hold individuals accountable with fairness, empathy, and room for growth. Navigating the social media landscape demands recognizing our power as consumers and creators. By fostering respect, empathy, and critical thinking, we can shape these phenomena into forces for positive change rather than division. It’s our responsibility to cultivate a digital space promoting healthy admiration, thoughtful dialogue, and accountability, transcending the boundaries of stan and cancel culture toward a more inclusive online community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358483edd787" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enums 101: A Beginner’s Guide to Named Constants in Programming]]></title>
            <link>https://blog.devgenius.io/enums-101-a-beginners-guide-to-named-constants-in-programming-732ea5aeab7e?source=rss-ea43bc51c3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/732ea5aeab7e</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Endurance, the Martian]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 15:13:03 GMT</pubDate>
            <atom:updated>2023-12-01T09:26:23.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8UuEV8O_e2YR9tAs" /><figcaption>Photo by <a href="https://unsplash.com/@bkaufhold?utm_source=medium&amp;utm_medium=referral">Burkhard Kaufhold</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Think about the last time you ordered food online, eagerly tracking its journey from the restaurant’s kitchen to your doorstep. The excitement you get when the order status changes from ‘Order received’ to ‘On the way’ or ‘In transit’ is really something, isn’t it? These status updates are like signposts, guiding you through the progress of your order.</p><p>While building software, we have our own set of signposts, they are called constants. Think of them as fixed points helping us navigate through our code. Enums, short for ‘enumerations’, represent a special kind of named constant — a versatile tool for bringing order and clarity to your codebase. They act like predefined options, maintaining order and, most importantly, making your code significantly more comprehensible to people with little to no programming experience.</p><p>This article serves as a beginner-friendly introduction to enums in programming. We’ll delve into what enums are, why they prove useful, and how you can define and apply them in your code. By the end of this read, you’ll have a robust understanding of enums, ready to use them in your next project.</p><h3>Demystifying Enums</h3><h4>Defining Enums: What Are They Exactly?</h4><p>Building upon the metaphorical signposts aiding code navigation, <a href="https://www.thoughtco.com/what-is-an-enum-958326">ThoughtsCo</a> defines enums as:</p><blockquote><em>An enum is a user-defined type consisting of a set of named constants called enumerators.</em></blockquote><p>Enumerators allow you to represent a finite set of options — be it days of the week, months of the year, or status updates in your preferred food delivery app. They operate as a pre-established catalog of choices, ensuring your code not only functions effectively but does so intuitively.</p><h4>Why Enums Stand Out</h4><p>Take into consideration, that we are building a support system to handle support messages from users, we have to store days of the week and month of the year in order to map and filter supports easily, but we stored them as strings instead of enums. As the app grows significantly larger, we start to face problems of accidental misspelling that prevents users from properly selecting months or days. Enums are a special data type that resolves this problem, they represent all choices or options in code as integers or strings (we will talk about this later in the article). Each of these options or choices has a name, in this case, days of the week or months of the year, thereby eliminating any future misspelling.</p><h3>Creating Enums</h3><p>The way enums are written varies across different programming languages, but they generally follow similar structures. They are typically declared using the <em>enum</em> keyword, and each choice i.e. individual values within the enum are listed inside curly braces. As we mentioned earlier, enums can have different underlying data types, while some other programming languages allow them to be based on strings.</p><h4>Backed vs. Non-Backed Enums</h4><p>Backed enums associate each individual value or constant with a specific underlying value, which can be either an integer or a string. On the other hand, non-backed enums rely on the order of declaration, following the sequence or order of increments.</p><h4>Writing your First Enum</h4><p>Defining enums involves creating a class, this class starts with a name and has a list of choices with each being a constant. Let’s explore how to write enums in popular programming languages like Python, PHP, TypeScript, and Java.</p><ul><li><strong>Python:</strong> In Python, enum initialization is simple. You can assign any valid Python object to an enum constant. Here’s an example:</li></ul><pre>from enum import Enum<br><br>class DaysOfWeek(Enum):<br>    MONDAY = &quot;Monday&quot;<br>    TUESDAY = &quot;Tuesday&quot;<br>    WEDNESDAY = &quot;Wednesday&quot;<br>    THURSDAY = &quot;Thursday&quot;<br>    FRIDAY = &quot;Friday&quot;<br>    SATURDAY = &quot;Saturday&quot;<br>    SUNDAY = &quot;Sunday&quot;</pre><p>In this example, each day is initialized with a string representing the day. Accessing an enum value in Python is done using the dot notation:</p><pre>print(DaysOfWeek.MONDAY.value)  # Output: Monday</pre><p>Python enums also provide methods like <strong>name</strong> to get the name of an enum constant:</p><pre>print(DaysOfWeek.MONDAY.name)  # Output: MONDAY</pre><ul><li><strong>TypeScript:</strong> In TypeScript, enums can be initialized with numeric or string values. Let’s look at an example:</li></ul><pre>enum DaysOfWeek {<br>    MONDAY = &quot;Monday&quot;,<br>    TUESDAY = &quot;Tuesday&quot;,<br>    WEDNESDAY = &quot;Wednesday&quot;,<br>    THURSDAY = &quot;Thursday&quot;,<br>    FRIDAY = &quot;Friday&quot;,<br>    SATURDAY = &quot;Saturday&quot;,<br>    SUNDAY = &quot;Sunday&quot;<br>}</pre><p>Accessing an enum value in TypeScript is similar to Python:</p><pre>console.log(DaysOfWeek.MONDAY);  // Output: Monday</pre><p>TypeScript enums provide methods like <strong>toString</strong> to get the name of an enum constant:</p><pre>console.log(DaysOfWeek.MONDAY.toString());  // Output: MONDAY</pre><ul><li><strong>PHP:</strong> PHP enums were introduced in PHP 8.1. Here’s how you can initialize an enum in PHP:</li></ul><pre>enum DaysOfWeek: string {<br>    case MONDAY = &#39;Monday&#39;;<br>    case TUESDAY = &#39;Tuesday&#39;;<br>    case WEDNESDAY = &#39;Wednesday&#39;;<br>    case THURSDAY = &#39;Thursday&#39;;<br>    case FRIDAY = &#39;Friday&#39;;<br>    case SATURDAY = &#39;Saturday&#39;;<br>    case SUNDAY = &#39;Sunday&#39;;<br>}</pre><p>Accessing an enum value in PHP is similar to other languages:</p><pre>echo DaysOfWeek::MONDAY;  // Output: Monday</pre><p>PHP enums also provide methods like <strong>name</strong> to get the name of an enum constant:</p><pre>echo DaysOfWeek::MONDAY-&gt;name;  // Output: MONDAY</pre><ul><li><strong>Java:</strong> In Java, enum initialization involves creating a Java enum class:</li></ul><pre>public enum DaysOfWeek {<br>    MONDAY(&quot;Monday&quot;),<br>    TUESDAY(&quot;Tuesday&quot;),<br>    WEDNESDAY(&quot;Wednesday&quot;),<br>    THURSDAY(&quot;Thursday&quot;),<br>    FRIDAY(&quot;Friday&quot;),<br>    SATURDAY(&quot;Saturday&quot;),<br>    SUNDAY(&quot;Sunday&quot;);<br><br>    private final String day;<br><br>    DaysOfWeek(String day) {<br>        this.day = day;<br>    }<br><br>    public String getDay() {<br>        return day;<br>    }<br>}</pre><p>Accessing an enum value in Java is similar to other languages:</p><pre>System.out.println(DaysOfWeek.MONDAY.getDay());  // Output: Monday</pre><p>Java enums provide methods like <strong>name</strong> to get the name of an enum constant:</p><pre>System.out.println(DaysOfWeek.MONDAY.name());  // Output: MONDAY</pre><p>In summary, writing enum varies slightly across programming languages, but the principles remain consistent. Although all these examples are for backed enums, for non-backed enums each of the constants does not have an underlying value. Let’s take a look at these examples again but “non-backed”</p><ul><li><strong>Python:</strong></li></ul><pre>from enum import Enum, auto<br><br>class Days(Enum):<br>    Monday = auto()<br>    Tuesday = auto()<br>    Wednesday = auto()<br>    Thursday = auto()<br>    Friday = auto()<br>    Saturday = auto()<br>    Sunday = auto()<br><br># Accessing Enum Values<br>print(Days.Monday)  # Output: Days.Monday<br><br># Iterating Over Enum<br>for day in Days:<br>    print(day)</pre><ul><li><strong>TypeScript:</strong></li></ul><pre>enum Days {<br>  Monday,<br>  Tuesday,<br>  Wednesday,<br>  Thursday,<br>  Friday,<br>  Saturday,<br>  Sunday,<br>}<br><br>// Accessing Enum Values<br>console.log(Days.Monday);  // Output: 0<br><br>// Iterating Over Enum<br>for (let day in Days) {<br>  console.log(day);<br>}</pre><ul><li><strong>PHP:</strong></li></ul><pre>enum Days {<br>    case Monday;<br>    case Tuesday;<br>    case Wednesday;<br>    case Thursday;<br>    case Friday;<br>    case Saturday;<br>    case Sunday;<br>}<br><br>// Accessing Enum Values<br>echo Days::Monday-&gt;name;  // Output: Monday</pre><ul><li><strong>Java:</strong></li></ul><pre>public enum Days {<br>   Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;<br><br>    // Iterating Over Enum<br>    static {<br>        for (Days day: Days.values()) {<br>            System.out.println(day);<br>        }<br>    }<br>}<br><br>public static void main(String[] args) {<br>    System.out.println(Days.Monday); // Output: Monday<br>}</pre><p>In non-backed enums, values are implicitly assigned based on their order of declaration. Accessing enum values is straightforward, and iterating over enum constants provides a clear understanding of their sequence. These examples showcase the simplicity and flexibility of non-backed enums across different programming languages.</p><h3>Real-world Use Cases</h3><p>Use cases in the real world for enum are very common, and important pieces of software. Look at it like a state machine, you use these constants to clearly define possible states and transitions.</p><ul><li><strong>Enums in E-commerce Order Tracking:</strong> Imagine you ordered a meal from your favourite restaurant online. The status changes from “Order Placed” to “Processing” and finally to “Shipped.” The fluid transition is managed by the enum behind the scene. Let’s take a look at how enums will be used in an order tracking system for an e-commerce system using Typescript:</li></ul><pre>enum OrderStatus {<br>  PLACED,<br>  PROCESSING,<br>  SHIPPED,<br>  DELIVERED,<br>  CANCELED,<br>}</pre><p>Each order status is represented by a unique constant. For instance, <strong>OrderStatus.SHIPPED</strong> indicates that your long-awaited package is on its way. To use the enums in your code, follow the example below:</p><pre>let currentOrderStatus = OrderStatus.PLACED;  <br><br>// ... After processing ... <br>currentOrderStatus = OrderStatus.PROCESSING;  <br><br>// ... When the order is shipped ... <br>currentOrderStatus = OrderStatus.SHIPPED;  <br><br>// ... Finally delivered ... <br>currentOrderStatus = OrderStatus.DELIVERED;</pre><ul><li><strong>Enums in Event RSVP Systems:</strong> Now, let’s jump into the world of event planning. Hosting a party? Organizing a tech meetup? Enums can simplify the RSVP system. For instance, the techies reading these who attended DevFest (in whichever country you are reading from), enums control how the status for the ticket is assigned. Let’s take a look at how this can be implemented in PHP:</li></ul><pre>enum RsvpStatus: string {<br>    case YES = &#39;Yes&#39;;<br>    case MAYBE = &#39;Maybe&#39;;<br>    case NO = &#39;No&#39;;<br>}</pre><p>Here, <strong>RsvpStatus</strong> acts as our pseudo-enum, representing the various RSVP responses attendees can choose from. Now, let&#39;s see how we can handle RSVPs using our PHP &quot;enum.”</p><pre>$rsvpStatus = RsvpStatus::YES;  <br><br>// ... Guest changes their mind ... <br>$rsvpStatus = RsvpStatus::NO;  <br><br>// ... A maybe turns into a yes ... <br>$rsvpStatus = RsvpStatus::YES;</pre><ul><li><strong>Enums in Transportation Booking:</strong> Ever booked a ride or flight online? Enums streamline the process, ensuring that your mode of transport is accurately represented. Let’s take a look at an example using Python as the language of reference:</li></ul><pre>from enum import Enum<br><br>class TransportMode(Enum):   <br>  CAR = &quot;Car&quot;   <br>  BIKE = &quot;Bike&quot;   <br>  PLANE = &quot;Plane&quot;   <br>  TRAIN = &quot;Train&quot;</pre><p>This Python enum represents different modes of transportation. To use this enum in your code, you do the following:</p><pre>selected_transport = TransportMode.CAR<br>  <br># ... Switching to a different mode ... <br>selected_transport = TransportMode.PLANE  <br><br># ... Back to ground with a bike ... <br>selected_transport = TransportMode.BIKE</pre><p>Enums make it easy to handle transportation choices, ensuring that your code aligns with the available options. Also gives you the ability to add more options in the future.</p><h4>Conditional Statements with Real-World Use Case</h4><p>In languages like Python, TypeScript, Java, or PHP, enums can be easily used in conditional statements. For instance, consider a scenario where you need to implement logic based on different user roles:</p><pre>enum UserRole {<br>  ADMIN = &#39;admin&#39;,<br>  MODERATOR = &#39;moderator&#39;,<br>  USER = &#39;user&#39;,<br>}<br><br>function checkAccess(role: UserRole): void {<br>  switch (role) {<br>    case UserRole.ADMIN:<br>      console.log(&#39;Full access granted!&#39;);<br>      break;<br>    case UserRole.MODERATOR:<br>      console.log(&#39;Limited access as a moderator.&#39;);<br>      break;<br>    case UserRole.USER:<br>      console.log(&#39;Basic user access.&#39;);<br>      break;<br>    default:<br>      console.log(&#39;Unknown role!&#39;);<br>  }<br>}<br>// Usage<br>checkAccess(UserRole.ADMIN);</pre><h3>Why Not Database Enums?</h3><p>After careful consideration and numerous debates with my friends, the preference for using <strong>enum</strong> in code over employing database enums boils down to readability and scalability. In databases, you have the option to create a column with the data type enum, allowing you to specify a list of acceptable options for that column. However, when the database is migrated and in production, modifying or adding constants to the enum affects all records in that table. For example, if you are an e-commerce provider serving various small businesses and you want to add a new status like &quot;RETURN&quot; to your enum in the database, you&#39;d have to alter millions of records. Now, the issue becomes apparent.</p><p>What’s the alternative? This is where <strong>smallint</strong> or <strong>tinyint</strong> comes into play. You can use backed enums to represent these constants and use them throughout your code. While they are stored in the database as <strong>smallint</strong> or <strong>tinyint</strong>, they are cast as enum constants in your code.</p><p>Examining this concept of using enums reveals that it not only brings more clarity to your code and allows for future scalability, but it also conserves database space and enhances speed. Enums are stored in databases as integers rather than strings, thereby occupying less space. Although this approach is specific to certain use cases and serves as a suggestion, there are instances where using a database enum might be preferred.</p><p>Database enums can be preferred in various scenarios. In a situation where you want to maintain referential integrity by restricting a column’s possible values to a stable set, minimizing the risk of invalid or misspelled data. For systems relying on centralized data management, especially when overseen by administrators or data architects, database enums provide a centralized hub for managing constants.</p><p>They’re also your go-to when dealing with older systems or tools expecting specific text values. Database enums make sure everything works nicely without a major code overhaul. Think about it: for heavy-duty tasks like data analysis and reporting, database enums bring clarity with human-friendly text values, skipping the need for extra steps. Plus, they get along better with certain database tools, making your life easier. Even in a world of microservices sharing a database, database enums keep everything in sync without needing a team huddle. Each of these instances only proves advantageous for this specific use case.</p><h3>Enum Best Practices</h3><p>Like any tool, there are best practices to follow so as not to go past the guidelines, same is for enum. To use enum perfectly, these are the best practices to follow.</p><ol><li><strong>Use Enums for Finite Sets</strong>: Enums are most effective when representing a fixed, finite set of related constants. It isn’t a good idea to use enums for open-ended sets, as this may lead to unintended consequences.</li><li><strong>Naming Convention:</strong> Choosing a meaningful name for your enum constants is very important. Enum values should be pretty self-explanatory and follow naming conventions that adhere to your project’s style guide.</li><li><strong>Document Enum Purpose</strong>: Include comments or documentation explaining the purpose of the enum and the meaning behind each constant. This aids other developers who might work with the code in the future to better understand it.</li><li><strong>Avoid Redundancy</strong>: If an enum’s purpose aligns with an existing language feature, like <strong>boolean</strong> values or numeric constants, consider whether an enum is truly necessary.</li><li><strong>Consistent Casing</strong>: Keep the casing consistent across enum constants. Whether using uppercase or camel case, uniformity improves visual appeal and maintains code consistency.</li></ol><h3>Conclusion</h3><p>In this article, we discussed what enums are, how to use them in your code with code examples, and how important they are to building software. Imagine trying to manage distinct choices or lists without enums — it’s like trying to organize a chaotic library without a proper catalog system! Whether you’re crafting an e-commerce order tracking system, streamlining RSVP processes for events, or ensuring data integrity in diverse scenarios, enums are your go-to. As we wrap up this article remember that enums not only bring clarity and scalability to code but also perform a vital role in database management when the situation calls for it. Looking forward to you using enum as a vital piece in your next software project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=732ea5aeab7e" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/enums-101-a-beginners-guide-to-named-constants-in-programming-732ea5aeab7e">Enums 101: A Beginner’s Guide to Named Constants in Programming</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>