<?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 Vijay Rangan on Medium]]></title>
        <description><![CDATA[Stories by Vijay Rangan on Medium]]></description>
        <link>https://medium.com/@vijay-rangan?source=rss-ae0a1608778f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4FiOIfY7tQGOArBjyp1OHA.jpeg</url>
            <title>Stories by Vijay Rangan on Medium</title>
            <link>https://medium.com/@vijay-rangan?source=rss-ae0a1608778f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:58:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vijay-rangan/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[Tech Debt Slowing You Down? 5 Ways To Repay]]></title>
            <link>https://vijay-rangan.medium.com/tech-debt-slowing-you-down-5-ways-to-repay-52a2a492b6be?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a2a492b6be</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-consulting]]></category>
            <category><![CDATA[tech-debt]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Fri, 03 May 2024 03:31:36 GMT</pubDate>
            <atom:updated>2024-05-03T03:31:36.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sYODTweF7lFj8KnU" /><figcaption>Photo by <a href="https://unsplash.com/@moneyphotos?utm_source=medium&amp;utm_medium=referral">rc.xyz NFT gallery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a CTO or co-founder of a rapidly growing startup, you know how quickly technology can become a burden rather than a benefit. It’s easy to get bogged down in technical debt, where outdated code and inefficient processes hold your team back from achieving their full potential.</p><p>As a CTO and software partner, I have seen this all too often. I’m here to share some hard-won lessons on how to avoid the pitfalls of tech debt and stay ahead of the curve</p><p>Assess Your Technical Debt</p><p>Before you can fix your technical debt, you need to know what it is. Take a step back and conduct an honest assessment of your current technology stack. What are the outdated systems, legacy code, or inefficiencies that are holding you back? Prioritize these issues based on their impact on your business.</p><p><strong>Prioritize Your Technical Strategy</strong></p><p>Your technical strategy should align with your overall business goals. What do you want to achieve in the next 6–12 months? Do you need to improve customer experience, increase scalability, or enhance security? Make sure your technical roadmap supports these objectives and sets your team up for success.</p><p><strong>Focus on Automation and Efficiency</strong></p><p>As your startup grows, manual processes become increasingly inefficient. Identify areas where automation can streamline workflows, reduce errors, and free up resources for more strategic tasks. Leverage tools like AWS CDK, Zapier, Terraform, ArgoCD etc to automate repetitive tasks and focus on high-value activities.</p><p><strong>Invest in Your Team’s Development</strong></p><p>Your team is your greatest asset. Invest in their growth by providing training opportunities, workshops, internal knowledge sharing sessions and conferences that align with your technical strategy. This not only improves individual skills but also fosters a culture of continuous learning and innovation within your organization.</p><p><strong>Stay Agile and Adaptable</strong></p><p>The tech landscape is constantly evolving. Stay ahead of the curve by embracing an agile mindset and being open to new ideas, frameworks, and tools. Encourage experimentation, fail fast, and learn from your mistakes. This is further made possible by creating a framework for quick iteration through automation.</p><p>In conclusion, avoiding tech debt requires a combination of strategic planning, automation, investment in your team’s development, and a willingness to adapt to changing circumstances.</p><p>What are some common challenges you’ve faced with technical debt? Share your experiences and insights below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a2a492b6be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategies for Enterprise Modernisation]]></title>
            <link>https://vijay-rangan.medium.com/strategies-for-enterprise-modernisation-4825e2328db5?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4825e2328db5</guid>
            <category><![CDATA[legacy]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <category><![CDATA[legacy-modernization]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 08:32:07 GMT</pubDate>
            <atom:updated>2024-04-29T08:32:07.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xkr8gnGmAtdB6IfD" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Many enterprises are saddled with systems that are becoming increasingly costly to maintain and do not support new business requirements or technologies. The challenge, however, is to modernise these systems without disrupting current operations, ensuring data integrity and minimal downtime.</p><h3>Introduction</h3><p>Legacy systems that have been the backbone of business operations for years, are now showing their age — becoming costly to maintain and increasingly difficult to adapt to modern demands.</p><p>I have witnessed the struggles these systems impose on organisations striving to stay relevant and competitive. In this article, I layout out why you need to modernise your tech stack and offer strategies to navigate the transition effectively.</p><h3>Why?</h3><p>Legacy systems are not merely relics of the past; they often contain critical business logic, data, and processes that have evolved over time. The challenge is to modernise these systems without compromising their integrity or the continuity of business operations.</p><p>Here’s why I think it is a pressing concern:</p><ol><li>Maintenance Costs: The cost of maintaining legacy systems can escalate rapidly as they often require specialised knowledge and resources that are becoming increasingly scarce and expensive.</li><li>Operational Risk: Legacy systems may be vulnerable to security threats, and their obsolescence can pose significant operational risks that need to be mitigated.</li><li>Business Agility: As markets evolve and customer expectations change, the inflexibility of legacy systems can hinder an organisation’s ability to respond swiftly to new opportunities or challenges.</li><li>Technology Integration: Modernising legacy systems involves integrating them with contemporary technologies, which can be a daunting task due to compatibility issues and the need for re-platforming.</li></ol><h3>Strategies for Effective Modernisation</h3><p>As with all problems, breaking it down to its core and following a step-by-step approach ensures that each part of the issue is addressed effectively before moving on to the next, ultimately leading to a comprehensive and successful resolution.</p><p>Following are some steps you can take to modernise your systems, considering both immediate and long-term objectives.</p><h3>Assessment and Planning</h3><p>Conduct a thorough assessment of the current legacy systems to understand the architecture, data, and dependencies. This will inform a tailored plan that aligns with business goals and technical realities. This could involve:</p><ul><li>Creating an inventory of assets — hardware, software, data etc</li><li>Performing a technical audit</li><li>Assessing business impact</li><li>Engaging with key stakeholders</li></ul><p>Consider running pilot projects or proofs of concept to validate assumptions, demonstrate potential improvements, and refine the modernisation approach before full scale implementation.</p><h3>Incremental Adoption</h3><p>Adopting an incremental approach to modernisation offers a path that is both prudent and effective. Breaking down the transition into smaller, phased migrations can significantly reduce the risk associated with such a transformative process. It provides the luxury of learning from each increment, fine-tuning the approach based on real-world feedback, and making necessary adjustments along the way.</p><p>In addition, this enables continuous delivery of updated features, which is essential in today’s fast-paced business environment. By focusing on one part of the system at a time, you can deliver new functionalities and improvements regularly without the fear of disrupting the entire system.</p><h3>Leveraging Micro services Architecture</h3><p>Micro services architecture can be a transformative approach to building and deploying applications when moving from a legacy system.</p><p>They allow you to modernise a part of the stack at a time and still offer interoperability with legacy systems without direct coupling. Creating an interface or adapter layer to interact with legacy systems, enables new micro services to consume data or services from older parts of the application.</p><p>This approach can improve modularity, scalability, and maintainability while allowing you to integrate modern technologies at your own pace.</p><p>This lends itself nicely to an incremental approach.</p><h3>Cloud Migration</h3><p>Migrating, either partially as a hybrid model or fully moving to the cloud allows enterprises to integrate emerging technologies such as AI, machine learning, elastic scalability, allows use of modern databases and other cloud-native offerings.</p><p>Evaluate cloud migration options that can provide better performance, reliability, and cost savings.</p><h3>Data Management and Compliance</h3><p>With the increased volume and sensitivity of data being processed, it’s crucial to have robust mechanisms in place for encryption, access control, and compliance with data protection regulations like GDPR and CCPA. This protects both the organisation and its customers from potential breaches.</p><p>Ensure that data management practices are up to date with current regulations and standards during the migration process to maintain compliance and data integrity.</p><p>Moving to the cloud makes this step easier since all major cloud vendors have this baked in to their service offerings.</p><h3>Security and Risk Mitigation</h3><p>Security and Risk Mitigation is of paramount importance in the context of transitioning from legacy systems.</p><p>Legacy systems can often be more vulnerable to security threats due to outdated security protocols. It is important to ensure that the new architecture does not inherit or even exacerbate their security vulnerabilities.</p><p>Cyber threats are constantly evolving, and a static defence may become obsolete quickly. Micro services architecture supports continuous monitoring and rapid response to security incidents, enabling organisations to stay ahead of potential vulnerabilities.</p><p>As technology evolves, so do cyber threats. By prioritizing security in the process, you can build a system that not only meets today’s needs but is also prepared to adapt to future challenges and threats.</p><h3>Change Management and Training</h3><p>Modernisation is not just about technology; it’s a cultural shift that requires buy-in from all levels of an organisation. Change management ensures that this shift aligns your company’s values, goals, and work culture, facilitating a smoother transition and higher acceptance rates.</p><p>It is particularly important when using the micro services approach because it addresses the human aspect of transformation as well, which can often be the most challenging part. Effective change management involves clear communication about why the legacy system is being replaced, the benefits the new architecture provides, and what changes staff members can expect. This clarity helps in reducing uncertainty and fear that often accompany a fundamental organisational change.</p><p>Implement a change management strategy to guide your team through the transformation. Provide training and resources to help employees adapt to new technologies and processes.</p><h3>Conclusion</h3><p>Modernisation is not just about upgrading technology; it’s about reinventing the foundation of your enterprise’s digital capabilities.</p><p>By taking a strategic and phased approach, organisations can navigate this complex process with confidence, ensuring that their systems are robust, secure, and capable of driving innovation for years to come.</p><p>As we stand at the crossroads of tradition and innovation, it’s imperative to make informed decisions that will propel your enterprise forward. With the right strategy and guidance, legacy systems can be transformed into a source of strength and agility in an ever-changing digital world.</p><p>What steps are you taking to modernise your tech stack?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4825e2328db5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Surprising Truth about JavaScript Promises]]></title>
            <link>https://vijay-rangan.medium.com/the-surprising-truth-about-javascript-promises-d23152fc6b25?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d23152fc6b25</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 07:28:30 GMT</pubDate>
            <atom:updated>2024-02-05T07:28:30.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XSuWdYa8wYDgNltc" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As developers, we often work with promises and callbacks in our code. While they may seem similar at first glance, there are some important differences to keep in mind. In this article, we will explore these differences and gain a deeper understanding of how promises and callbacks work.</p><p>Through an execution order experiment, we will examine the task queue versus the microtask queue and how they impact the behavior of callback functions and promises. By the end of this article, we will have a clear understanding of the promise mechanism and the microtask queue, as well as how they differ from callback functions and the task queue.</p><h3>Key Takeaways</h3><ul><li>Promises and callbacks have important differences in how they execute in code.</li><li>The microtask queue runs before the task queue, impacting the order of execution.</li></ul><h3>Execution Order Experiment</h3><p>I setup an experiment to observe the execution order of promises and callbacks. The sample code below sets up a promise that logs a value and a callback function that uses setTimeout to log the same value.</p><pre>const promise = new Promise(resolve =&gt; {<br>  resolve(&#39;promise value&#39;);<br>});<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;setTimeout value&#39;);<br>}, 0);<br><br>promise.then(value =&gt; {<br>  console.log(value);<br>});</pre><p>At first glance, it may seem that the order of execution would be the same regardless of the order of the code. However, the order of execution is actually dependent on the type of queue being used.</p><p>Depending on the type of async mechanism you use, one of two queues are used internally</p><ol><li>Microtask queue — or —</li><li>Task queue (aka Macrotask queue)</li></ol><p>The main difference between the microtask queue and the task queue is that every task that’s been queued up in the microtask is run first, irrespective of how many items are there in the task queue.</p><p>To test this, I switched the order of the code and ran it again:</p><pre>setTimeout(() =&gt; {<br>  console.log(&#39;setTimeout value&#39;);<br>}, 0);<br><br>const promise = new Promise(resolve =&gt; {<br>  resolve(&#39;promise value&#39;);<br>});<br><br>promise.then(value =&gt; {<br>  console.log(value);<br>});</pre><p>The result is still the same. From this it is clear that promises use the microtask queue, while callbacks like setTimeout use the task queue. This is why the setTimeout function always runs after the Promise.</p><p>Understanding this difference between the task queue and the microtask queue is important when working with promises and callback functions. It can help prevent unexpected behavior and ensure that our code runs as intended.</p><p>If you’re the kind of person that likes consuming tech content via videos, you can find a video of this on my YouTube channel.</p><p>YouTube link : <a href="https://www.youtube.com/watch?v=6lsTRTUNHgk&amp;t=5s">The Surprising Truth about JavaScript Promises</a></p><p>If you liked this article and you learned something, don’t be shy… show some love with a 👏 😀</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d23152fc6b25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⏩ Boost NodeJS Performance with Threads]]></title>
            <link>https://vijay-rangan.medium.com/boost-nodejs-performance-with-worker-threads-29d21ec4ffd2?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d21ec4ffd2</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 08:58:12 GMT</pubDate>
            <atom:updated>2023-08-04T15:04:15.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUK887QKv5G2J6I70mSugw.jpeg" /></figure><p>NodeJS is known for its non-blocking, event-driven architecture, making it a popular choice for building scalable and high-performance applications. However, when it comes to handling computationally intensive tasks or large-scale data processing, the single-threaded nature of NodeJS can become a bottleneck.</p><p>Fortunately, NodeJS provides a solution in the form of Worker Threads, which enable developers to harness the power of multi-threading to improve performance and process data more efficiently.</p><p>Today I will walk you through how I used worker threads to significantly boost the performance of a real world problem that I solved for one of my clients.</p><blockquote>Need a consultant CTO or FAANG-tier engineer to build your MVP? Get in touch — cto@vijayrangan.dev</blockquote><p>We’ll be generating training data for a ML model for anomaly detection. If you’re familiar with ML at all, you’ll know that we need large amounts of data for the model to do it’s job well.</p><p>All the code I’ve used in this post is availble at <a href="https://github.com/vjrngn/node-worker-threads">https://github.com/vjrngn/node-worker-threads</a></p><h3>Approach</h3><p>To truly understand the benefits of using threads, we will create two versions of our NodeJS application.</p><ol><li><strong>Single-Threaded Version:</strong> A straightforward implementation that processes the entire dataset sequentially on the main thread.</li><li><strong>Multi-Threaded Version:</strong> We will leverage <a href="https://nodejs.org/api/worker_threads.html">Worker Threads</a> to distribute the workload across multiple threads.</li></ol><h3>Setup</h3><p>We’ll generate 10,00,000 (1 million) records of random transaction data. We will split the workload across multiple threads instead of using just a single thread.</p><p>To generate random data, we’ll use the popular <a href="https://fakerjs.dev/">Faker</a> library. If you’re following along, paste the following code in a file named random-data-generator.js .</p><pre>const { faker } = require(&#39;@faker-js/faker&#39;);<br>const numTransactions = 1000000;<br>const numSellers = 1000;<br>const numCustomers = 10000;<br><br>// Generate a set of 1000 unique sellers (or merchants)<br>const sellers = Array.from({ length: numSellers }).map(() =&gt; {<br>  return {<br>    id: faker.string.uuid(),<br>    accountId: faker.string.uuid()<br>  }<br>});<br><br>// Generate a set of 10,000 unique customers<br>const customers = Array.from({ length: numCustomers }).map(() =&gt; {<br>  return {<br>    id: faker.string.uuid(),<br>    accountId: faker.string.uuid()<br>  }<br>});<br><br>Array.from({ length: numTransactions }).map(() =&gt; {<br>  return {<br>    id: faker.string.uuid(),<br>    timestamp: faker.date.past({ years: 1 }).toLocaleDateString(),<br>    customerId: faker.helpers.arrayElement(customers.map(c =&gt; c.id)),<br>    customerAccountId: faker.helpers.arrayElement(customers.map(c =&gt; c.accountId)),<br><br>    // seller data<br>    sellerId: faker.helpers.arrayElement(sellers.map(s =&gt; s.id)),<br>    sellerAccountId: faker.helpers.arrayElement(sellers.map(s =&gt; s.accountId)),<br><br>    // transaction data<br>    amount: faker.number.float({ min: 1000, max: 100000 }),<br>    currencyCode: faker.finance.currencyCode(), // ISO 4217 currency code.<br>    paymentMethod: faker.helpers.arrayElement([<br>      &quot;CREDIT_CARD&quot;,<br>      &quot;DEBIT_CARD&quot;,<br>      &quot;UPI&quot;,<br>      &quot;BANK_TRANSFER&quot;<br>    ])<br>  };<br>});</pre><h3>🪡 Single-Threaded Approach</h3><p>This approach is straight forward. Let’s setup the following in index.js . The code only imports the module we created above.</p><pre>const startTime = Date.now();<br>require(&#39;./random-data-generator.js&#39;);<br>const endTime = Date.now();<br><br>console.log(`That took ${endTime - startTime}ms`);</pre><p>On my machine — a MacBook Pro M1 — the process takes <strong>69976ms</strong> (or 70 seconds). Not bad given we’re generating a million records. If this was an API call, it would be baaaad. Let’s see how threads can make this better 👇</p><p>🤫 On a side not, any module or file that is imported is immediately executed. Running node index.js imports the random-data-generator.jsand runs the loop that we have defined.</p><h3>🧵 <strong>Multi-Threaded Approach</strong></h3><p>Let’s modify our code as follows. In the index.js file, we’ll introduce the worker module. There’s quite a bit of change, so just come along for the ride for now and I’ll explain how this all fits together soon.</p><pre>const { Worker } = require(&#39;worker_threads&#39;);<br>const { faker } = require(&#39;@faker-js/faker&#39;);<br>const os = require(&#39;os&#39;);<br>const path = require(&#39;path&#39;);<br><br>const numTransactions = 1000000;<br>const numSellers = 1000;<br>const numCustomers = 10000;<br><br>const threads = os.cpus().length; // 1 thread per core<br><br>// Generate a set of 1000 unique sellers (or merchants)<br>const sellers = Array.from({ length: numSellers }).map(() =&gt; {<br>  return {<br>    id: faker.string.uuid(),<br>    accountId: faker.string.uuid()<br>  }<br>});<br><br>// Generate a set of 10,000 unique customers<br>const customers = Array.from({ length: numCustomers }).map(() =&gt; {<br>  return {<br>    id: faker.string.uuid(),<br>    accountId: faker.string.uuid()<br>  }<br>});<br><br>let transactions = [];<br>for (let i = 0; i &lt; threads; i++) {<br>  const startTime = Date.now();<br>  const worker = new Worker(<br>    path.resolve(__dirname, &#39;random-data-generator.js&#39;), {<br>      workerData: {<br>        numTransactions: numTransactions / threads,<br>        sellers,<br>        customers<br>      }<br>    }<br>  );<br><br>  worker.on(&#39;message&#39;, (data) =&gt; {<br>    transactions = transactions.concat(data);<br>  });<br><br>  worker.on(&#39;exit&#39;, () =&gt; {<br>    if (transactions.length === numTransactions) {<br>      const endTime = Date.now();<br>      console.log(`That took ${endTime - startTime}ms`);<br>    }<br>  })<br>}</pre><p>We need a few changes in our random-data-generator.js as well.</p><pre>const { faker } = require(&#39;@faker-js/faker&#39;);<br>const { workerData, parentPort } = require(&#39;worker_threads&#39;);<br><br>const { numTransactions, sellers, customers } = workerData;<br><br>const transactions = Array.from({ length: numTransactions }).map(() =&gt; {<br>  return {<br>    id: faker.string.uuid(),<br>    timestamp: faker.date.past({ years: 1 }).toLocaleDateString(),<br>    customerId: faker.helpers.arrayElement(customers.map(c =&gt; c.id)),<br>    customerAccountId: faker.helpers.arrayElement(customers.map(c =&gt; c.accountId)),<br><br>    // seller data<br>    sellerId: faker.helpers.arrayElement(sellers.map(s =&gt; s.id)),<br>    sellerAccountId: faker.helpers.arrayElement(sellers.map(s =&gt; s.accountId)),<br><br>    // transaction data<br>    amount: faker.number.float({ min: 1000, max: 100000 }),<br>    currencyCode: faker.finance.currencyCode(), // ISO 4217 currency code.<br>    paymentMethod: faker.helpers.arrayElement([<br>      &quot;CREDIT_CARD&quot;,<br>      &quot;DEBIT_CARD&quot;,<br>      &quot;UPI&quot;,<br>      &quot;BANK_TRANSFER&quot;<br>    ])<br>  }<br>});<br><br>parentPort.postMessage(transactions);</pre><p>Running node index.js with this yields a result of <strong>10831ms </strong>(or 10.8 seconds). That is orders of magnitude faster!</p><h3>🤔 How it works</h3><p>Alrighty, let’s dig in to the details.</p><pre>const { Worker } = require(&#39;worker_threads&#39;); </pre><p>We first start by creating an instance of the Worker class. The first argument of the constructor is the path to a script to be run by each thread (or worker).</p><pre>// threads = cores.length<br>for (let i = 0; i &lt; threads; i++) {<br>// ...<br>  const worker = new Worker(<br>    path.resolve(__dirname, &#39;random-data-generator.js&#39;), {<br>    workerData: {<br>      numTransactions: numTransactions / threads,<br>      sellers,<br>      customers<br>    }<br>   });<br>// ...<br>}</pre><p>In our experiment, we create as many threads as there are cores in our machine — const threads = os.cpus().length . This ensures that we take maximum advantage of all our processors by performing data generation in parallel.</p><pre>{<br>  workerData: {<br>    numTransactions: numTransactions / threads,<br>    sellers,<br>    customers<br>  }<br>}</pre><p>As the second argument, we configure each worker to process a subset of the total transactions, specified by numTransactions: numTransactions/ threads .</p><p>We want all our transactions to be between the same set of customers and sellers, so we move the fake customer and seller data to our main thread and pass them in as data to the worker. Next, we access this data in our worker script random-data-generator.js like so:</p><pre>const { workerData, parentPort } = require(&#39;worker_threads&#39;);<br><br>const { numTransactions, sellers, customers } = workerData;<br><br>// ...</pre><p>workerData can be used in worker threads and gives us access to the data we make available from the main thread.</p><p>NodeJS threads use messages to communicate with each other and the main thread. parentPort allows any worker threads to send messages to the main thread using the postMessage method. Notice in the random-data-generator.js file we have the following piece of code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZaRM_fC6xpj2fY2qA4HmQ.png" /></figure><p>This command sends the generated transactions from each worker back to the parent.</p><blockquote>Note: You may want to use a SharedArrayBuffer when dealing with threads and shared memory to ensure threads don’t step on each others toes and cause data corruption. Our example is simple and I’ve chosen to not use it.</blockquote><p>If you’re a visual learner like me, you will probably like the image below that provides a visualisation of the multi threaded approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DthLJFrFBmXJLlwW3WaV1w.png" /><figcaption>Visualisation of delegating work to threads in NodeJS</figcaption></figure><h3>Conclusion</h3><p>We saw how using threads to off-load CPU intensive tasks can significantly help speed up our application. NodeJS threads are great for these types of applications.</p><p>They are not a good candidate for I/O bound tasks — file and network — as the NodeJS engine (V8) will handle those a lot better.</p><p>In a future post, I will talk about NodeJS’s cluster module that allows us to horizontally scale our web applications to all available cores and maximise resource utilisation.</p><p>👉 GitHub Repo: <a href="https://github.com/vjrngn/node-worker-threads">https://github.com/vjrngn/node-worker-threads</a></p><p>If you liked this article and found it useful, don’t be shy… show some love with a 👏</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d21ec4ffd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka: Real World Patterns and Trade-offs]]></title>
            <link>https://vijay-rangan.medium.com/kafka-real-world-patterns-and-trade-offs-348fbd9c74a7?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/348fbd9c74a7</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[architecture-pattern]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 08:17:39 GMT</pubDate>
            <atom:updated>2023-07-01T19:29:01.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*IsMlfkb41IMKVVstzfMpsg.png" /></figure><p>In this article, we will look at 4 real world patterns using Kafka and the associated trade-offs. These patterns are inspired by large scale applications that I have personally architected and contributed to. We will explore the following patterns:</p><ol><li>Mono partition topics</li><li>Partitioning</li><li>Service-internal topics</li><li>The outbox pattern</li></ol><h3>Introduction</h3><p>If you aren’t already familiar, Apache Kafka is an open-source distributed event streaming platform used by thousands of companies around the globe for applications ranging from asynchronous service communication to data streaming pipelines for analytical workloads. <br>It has become a popular choice for building scalable and reliable distributed systems, especially in micro service architectures.</p><h3>1. Mono Partition Topics</h3><p>All messages produced to Kafka are stored in partitions. Partitions belong to a topic and a for all practical purposes, a topic is identified by it’s name. Therefore, you can think of a topic as a logical grouping of partitions.</p><p>Kafka topics ensure message ordering at a partition level and <strong>DOES NOT</strong> provide topic wide message ordering. This means if we have a topic with 4 partitions (like below), messages produced to this topic will be consumed based on the order of insertion in each of the partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgbR_PILoMpeIPAXLqKEPw.png" /><figcaption>Topic with 4 partitions with messages in each ordered from left to right</figcaption></figure><p>Kafka affords us the power to horizontally scale consumers. This is done by increasing the number of partitions in a topic — more partitions, more parallel processing by consumer groups. So, the concept of a “mono partition topic” is quite unintuitive. In some situations, however, it can be very useful.</p><p>Consider the scenario of capturing a continuous stream of modifications in a database table. To maintain a comprehensive audit trail of all database changes, say for a “users” table, a well-suited approach is to utilize a topic named “users_table_events” with a single partition. As new records are inserted, existing entries get updated, or data gets deleted within the table, a corresponding event is published as a message to this topic, preserving the sequential order in which they were executed.</p><p><strong>PROS:</strong></p><ol><li>Ordering Guarantee: Single partition topics provide strict message ordering since all messages are processed in a sequential manner within a single partition. This ensures that messages are consumed and processed in the exact order they were produced.</li><li>Simplified Consumer Logic: With a single partition topic, the consumer logic becomes simpler as there is no need to handle partition assignment and coordination among multiple partitions.</li><li>Guaranteed Message Processing: In failure scenarios, the processing of messages within a single partition is more deterministic and predictable compared to multi-partition topics. If a consumer encounters an error or needs to be restarted, it can simply resume processing from the last consumed message within the single partition, without worrying about synchronisation with other partitions.</li></ol><p><strong>CONS:</strong></p><ol><li>Limited Parallelism: Single partition topics restrict the parallelism and scalability of message processing since all messages are confined to a single partition. This can become a bottleneck if the message throughput is high.</li><li>Reduced Fault Tolerance: Single partition topics have limited fault tolerance capabilities compared to multi-partition topics. If the single partition becomes unavailable due to a broker failure or other issues, the entire topic becomes inaccessible. It is important to ensure appropriate monitoring and fault recovery mechanisms to mitigate the impact of potential failures.</li><li>Potential Performance Challenges: Single partition topics may experience performance challenges when dealing with high message throughput. As all messages are processed within a single partition, the processing speed of the consumer becomes a critical factor. Bottlenecks can occur if the consumer cannot process messages quickly enough, leading to latency and potential message backlogs.</li></ol><h3>2. Message ordering using partition keys</h3><p>Of all the patterns we’ll look at today, this is likely the most common one I’ve seen. In Kafka, partition keys are used by the producer client library to decide which partition a message is sent.</p><p>Common partitioning strategies:<br>1. Round-robin<br>2. Key based<br>3. Hash based<br>4. Custom partitioner</p><p>Each partitioning strategy carries with it it’s own trade-offs — a subject that deserves a post of its own. I’ll keep that little gem for another day.</p><p>By default, producers use a round-robin approach where each message is sent to one partition at a time. If a key is set during message production, then messages with the same key are always sent to the same partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whbUttYUGl4S2ItKc1wQjg.png" /><figcaption>Messages with the same key are always produced to the same partition</figcaption></figure><p>Kafka guarantees FIFO (First-In-First-Out) ordering for all messages that specify a partition key. This feature is particularly beneficial in domains such as accounting systems, as well as event sourcing. For example, processing financial transactions requires maintaining the correct account balances and order of operations. By using the account ID (say) as the partition key, all transactions related to a specific account will be processed sequentially, ensuring consistency and accurate balances.</p><p><strong>PROS:</strong></p><ol><li>Message Ordering: By carefully selecting a partition key, you can ensure that related messages with the same key are stored in and processed from the same partition. This guarantees the ordering of messages within a specific partition, enabling you to maintain the sequence of operations when required.</li><li>Parallel Processing: Kafka allows multiple partitions to be processed concurrently, providing horizontal scalability. By choosing partition keys wisely, you can distribute the workload across partitions, enabling parallel processing of messages by multiple consumers. This enhances the overall throughput and performance of the system.</li><li>Consumer Affinity: Partition keys can be used to achieve consumer affinity, meaning that messages with the same partition key are consumed by the same consumer instance, allowing for efficient state management and minimising redundant processing.</li></ol><p><strong>CONS:</strong></p><ol><li>Data Skew: There aren’t obvious cons with using partition keys but there are trade-offs depending on the strategy you choose. For instance, using key based strategy can lead to “hot partitions” where some partitions may receive a significantly higher volume of messages compared to others. such as higher volume of transactions by a few account IDs compared to others.</li><li>Limited Partition Count: Each Kafka topic has a fixed number of partitions, and the number of partitions determines the maximum parallelism and scalability of the topic. Choosing partition keys that result in too few partitions may limit the system’s ability to scale horizontally. On the other hand, having an excessive number of partitions may introduce unnecessary complexity and overhead. It is crucial to strike a balance by determining an appropriate partition count based on the anticipated workload and processing requirements.</li><li>Key Selection Complexity: Selecting effective partition keys requires careful consideration of the data and its characteristics. Choosing an inappropriate partition key can result in imbalanced workloads, poor performance, or increased data skew. It may also require domain-specific knowledge to identify suitable attributes that can be used as partition keys.</li></ol><h3>3. Service-internal topics</h3><p>This pattern is relatively uncommon but is employed at <strong>NuBank</strong> as a solution for handling time-consuming tasks within a service’s purview.</p><p>Instead of using topics to publish events for consumption by other services, this pattern leverages them as a means of offloading upfront work. By doing so, it reduces potentially expensive computations in exchange for improved response times to the caller. This approach essentially functions as a queueing mechanism while taking advantage of Kafka’s scaling capabilities.</p><p>Let’s dive into two how this was used at NuBank. But first, a little terminology.</p><p><em>Transactional environment: This term refers to the collection of microservices and their associated databases that deal with the application layer, serving real customers.</em></p><p><em>Analytical environment: This encompasses the environment and set of services dedicated to business analytics, big data, and the ETL (Extract, Transform, Load) process at NuBank.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBcagQW_-7SbgYnN0VxtJA.png" /><figcaption>Extraction service using internal topic to extract 300+ production databases</figcaption></figure><p>Within the data ingestion team at NuBank, we adopted this approach to schedule extractions of databases from the transactional environment. At regular intervals, we initiated the extraction process from over 300 microservices using the Datomic database. The process of extraction is, as you can imagine, a time-consuming operation.</p><p>Using service-internal topics, when the scheduler called the extraction service, a new batch of extractions was enqueued.</p><p>Once enqueued, the extraction service efficiently handled the time-consuming task of data extraction by processing all databases. This approach enabled us to promptly respond to the scheduler and efficiently handle large volumes of data from these databases by scaling out the consumers.</p><p><strong>PROS:</strong></p><ol><li>Flexibility and Agility: Private topics give services the flexibility to publish events specific to their needs without affecting other services and can evolve independently, adding or modifying private topics as needed.</li><li>Fine-grained Access Control: Private topics enable fine-grained access control, allowing only authorized services to produce or consume messages from the topic. This enhances security by preventing unauthorized access and ensuring that sensitive data or internal communication is restricted to the intended services.</li><li>Performance Optimization: Private topics can be optimized for specific use cases or performance requirements. Since only internal services are involved, you can configure the topic and broker settings based on the needs of these services, such as retention policies, replication factors, or message compression. This optimization can improve overall system performance and efficiency.</li></ol><p><strong>CONS:</strong></p><ol><li>Increased Complexity: Introducing private topics adds complexity to the overall system architecture. Managing additional topics and ensuring proper coordination between producers and consumers can become challenging. Proper documentation and communication are crucial to maintain a clear understanding of the purpose and usage of private topics across the organization.</li></ol><h3>4. Outbox pattern</h3><p>The Outbox pattern is used in micro services architecture to ensure reliable and consistent event-driven communication between services.</p><p>In this pattern, each service maintains an “outbox” within its own database. The outbox serves as a buffer where events or messages to be published asynchronously are stored. Instead of directly publishing messages to Kafka, the service writes the events to its outbox as part of a database transaction. This helps mitigate the problems associated with 2PC (two phase commit).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fW1nAOqOmlCI4gOGBTVfRg.png" /><figcaption>Service update it’s data and records this change within the same DB transaction</figcaption></figure><p><strong>PROS:</strong></p><ol><li>Data Consistency: By associating the outbox with the service’s own transaction, data changes and events are committed or rolled back atomically, ensuring consistency between data updates and event publication.</li><li>Fault Tolerance: In case of failures or downtime, the outbox processor can resume processing from the last successfully processed event, ensuring fault tolerance and message durability.</li><li>Scalability: The outbox processor can be horizontally scaled to handle high event volumes, ensuring efficient processing and distribution of events. (with the trade-off of synchronisation, detailed below)</li></ol><p><strong>CONS:</strong></p><ol><li>Increased Complexity: Implementing the Outbox pattern adds complexity to the system architecture. It introduces additional components, such as the outbox tables, outbox processor, and event publishing mechanism, which require development and maintenance efforts.</li><li>Latency: The Outbox pattern introduces an inherent delay in event publication. Events are not immediately published when data changes occur, as they need to be written to the outbox first and then processed by the outbox processor. Depending on the frequency of polling and the processing time of the outbox processor, there can be a slight delay between data changes and event delivery.</li><li>Synchronisation Challenges: The Outbox pattern requires synchronization between the service’s data changes and the events written to the outbox. Ensuring that events are correctly associated with the corresponding data changes can be challenging, especially in scenarios where distributed transactions or multi-step workflows are involved. Care must be taken to handle scenarios like compensating transactions or rollbacks to maintain consistency.</li></ol><p>Despite these challenges, the Outbox pattern remains a valuable approach for achieving reliable event-driven communication in a micro services world.</p><h3>Conclusion</h3><p>While there are many ways to use Kafka, it is important to carefully evaluate the specific requirements and trade-offs of the system you are working with before adopting any of these patterns; considering factors such as the scale, complexity, and performance needs of the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=348fbd9c74a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Testability: Practical Examples]]></title>
            <link>https://vijay-rangan.medium.com/boost-testability-practical-examples-e6db65c28c17?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6db65c28c17</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 16:45:42 GMT</pubDate>
            <atom:updated>2023-06-05T03:22:40.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52Iehhp_MclhVZsWKgcavw.jpeg" /></figure><h3>Boost Testability with Dependency Injection in JavaScript: Practical Examples</h3><p>You’ve likely <a href="https://vijay-rangan.medium.com/the-ultimate-guide-to-dependency-injection-without-libraries-fab3eafdedfe">read</a> that dependency injection (or DI) is this great tool that helps write better code. If you’re like me, having heard or read about this so… many… times but never seen or understood how it actually works, you’re in for a treat. Today, we’re going to look at some practical examples of how DI actually helps.</p><p>Welcome back, coding enthusiasts! Today we turn our attention to a crucial aspect of the use of DI: <strong>testability</strong>.</p><blockquote>Testability is all about making our code easy to test</blockquote><p>To illustrate this, we’ll revisit Jane’s Coffee Shop. So, grab your favourite cuppa joe ☕️ and let’s dive into the world of testability and dependency injection!</p><h3>Testing…</h3><p>“Testing, testing, testing” — we hear this so much. What does it even mean?</p><p>As programmers, we’re testing all the time — running a command on the terminal, testing an API with a tool like Postman etc… The only difference is that most of us are testing code manually. When I say testing, I mean automated testing.</p><p>By writing automated tests, we can verify the correctness of our code, catch bugs early on and ensure that future modifications don’t break existing functionality, in a way that is repeatable.</p><p>Testability, on the other hand, is about writing code that is easy to test. Dependency injection plays a pivotal role in achieving this.</p><h3>Quick Setup</h3><p>I personally like using <a href="https://jestjs.io/">Jest</a> and <a href="https://sinonjs.org/">Sinon</a> to write tests. Jest is a testing framework that’s easy to setup and work with, and so is Sinon.</p><p>If you aren’t familiar with these tools, don’t worry. You should be able to follow along either way.</p><p>Let’s add these tools to our project.</p><pre>yarn add -D jest sinon @types/jest</pre><p><em>Shameless plug: If you want to learn about how Sinon works, check out my </em><a href="https://www.youtube.com/watch?v=VLe9LxyO6Qo"><em>YouTube video</em></a><em> or </em><a href="https://medium.com/p/e6db65c28c17"><em>this article</em></a></p><p>Once that’s done, we’ll update the package.json file so we can easily run our tests from the CLI using npm run test , like so</p><pre>{<br>  &quot;name&quot;: &quot;coffee-shop&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;jest&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/jest&quot;: &quot;^29.5.2&quot;,<br>    &quot;jest&quot;: &quot;^29.5.0&quot;<br>  }<br>}</pre><p>Finally, we’ll add a test directory. Jest, by default, looks for test files in this directory and any file ending with .spec.js or .test.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*2Xph9cOTHqX6oP5Rc-Un8g.png" /><figcaption>The project structure for testing</figcaption></figure><h3>Your first test</h3><p>We’ll write tests for Jane’s Barista class.</p><p>If you read the <a href="https://vijay-rangan.medium.com/the-ultimate-guide-to-dependency-injection-without-libraries-fab3eafdedfe">prequel to this post</a>, you’ll remember that we decoupled the Baristaclass from the CoffeeGuruclass using DI. This has allowed us now to create a fake implementation of it’s dependencies and test it in isolation, ie, only focus on the Barista class and not worry about anything else.</p><p>In testing, we follow a structure called Arrange Act Assert . It simply means for each test, we</p><ol><li>Arrange — the world by creating instances, setting up seed data etc…</li><li>Act — call the function or class that we are testing. This is also called System Under Test (or SUT)</li><li>Assert — or make sure that the result from calling the SUT is what you expect it to be.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXZy7OX9zzwwbFFOdK-1ZQ.png" /></figure><p>Running the above with npm run test produces the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1jr300E-ndI0DmXebAONw.png" /></figure><p>Alright, alright. This is all fine and dandy but where is this “power of DI” that you speak of? I love your enthusiasm! Let’s dig in.</p><h3>Flexing the code</h3><p>One of the advantages of dependency injection is the ability to put our code through various scenarios. Let’s explore a test case where the Coffee Guru fails to provide coffee beans, forcing the Barista to handle the situation gracefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0kccCP1DexStd-bFS80vw.png" /></figure><p>As you can see, we modified CoffeeGuru to return an unexpected value. In the current implementation, this test fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwkBtha6kvxtUYBcXDBYlw.png" /></figure><p>This is an opportunity to go update our implementation to handle this situation. Let’s update our Barista class to handle this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxRYY-MSKDOSXFRYWulNCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSVuWLiZBLygluXei-0PSQ.png" /></figure><p>Finally, we’ll test another scenario where we simulate an error during the milk retrieval process. Once again, we update our test first to setup expectations from our code and see that our test fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoyhUQAkAugqSyG6JRx9zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIT3DhQFE8ewcwopx0lNug.png" /></figure><p>Now that we know this can happen, we’ll update our code to handle this by wrapping it in a try...catch block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNlitbr8JIb3bS3rAJBWJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AE_4U9Wq7BnPIZO4E-uUjQ.png" /></figure><p>There! Our tests are back to green.</p><p>If you didn’t notice, there’s a pattern here. Each of our examples above took the following shape:</p><ol><li>Write a test scenario</li><li>Run the test and see it fail</li><li>Update the code to handle the scenario</li><li>Re-run the test and see it pass.</li></ol><p>This cycle is known as the Red-Green-Refactor cycle and is the mantra of Test Driven Development.</p><h3>Conclusion</h3><p>By decoupling dependencies and replacing them with mocks or stubs (collectively called fakes), we can isolate and thoroughly test our code. The ability to simulate different scenarios and gracefully handle errors ensures the reliability and robustness of our applications. So, harness the potential of dependency injection and take your testing game to the next level!</p><p>I hope you’re now able to see how DI helps in the real world and got a good understanding of how to use it in the real world.</p><p>I’d love to know what you think about these articles! <br>Are they useful? What are you looking to learn more about? React, Node / Express / databases and ORMs?</p><p>I have been a full stack engineer for about 9 years and have a wide array of experience from web development with React and Vue to architecting micro services to setting up and automating infrastructure.</p><p>As always, if you liked this article and you learned something new, show some love with a 👏 . It really helps reach a wider audience and motivates me to write more. 🙌🏻</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6db65c28c17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ The Ultimate Guide to Dependency Injection Without Libraries!]]></title>
            <link>https://vijay-rangan.medium.com/the-ultimate-guide-to-dependency-injection-without-libraries-fab3eafdedfe?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab3eafdedfe</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Mon, 29 May 2023 10:15:38 GMT</pubDate>
            <atom:updated>2023-05-29T10:15:38.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcxPGjKlKvorMUW9DW9GUg.jpeg" /></figure><h3>Introduction</h3><p>Greetings, fellow developers! <br>Today, we embark on a journey into the realm of dependency injection in JavaScript, with no external libraries.</p><p>Brace yourself for an immersive exploration of this powerful technique as we delve into creating Jane’s Coffee Shop. With a touch of pragmatism and a sprinkle of technical finesse, we’ll unravel the secrets of dependency injection, enabling you to craft flexible, scalable, and maintainable JavaScript applications.</p><blockquote>Software, as opposed to hardware, is meant to be easily changeable. Hence the name.</blockquote><h3>Unveiling the Essence of Dependency Injection</h3><p>Before we dive into the practical implementation, let’s understand the essence of dependency injection.</p><p>Imagine Jane’s Coffee Shop, a bustling hub for caffeine enthusiasts. Jane, a coffee connoisseur, realises that she can’t excel in every aspect of her business single-handedly. Instead, she gets help from a coffee vendor (Coffee Guru) that provides the beans and a barista (Barista Bob) to turn those beans into ☕️. This allows Jane to focus on what she does best — running her business and serving delightful cups of coffee to her loyal customers — by delegating the responsibility of buying the beans, roasting them and finally grinding them to make coffee.</p><p>Much like how Jane depends on others to help with her business, in software development, your code has different components, objects and modules that depend on each other to function correctly.</p><h3>Setting the Stage</h3><p>To kickstart our journey, we lay the groundwork for our application. We initialise a simple NodeJS project called coffee-shop with the following directory structure. The code for it is available at <a href="https://github.com/vjrngn/coffee-shop">https://github.com/vjrngn/coffee-shop</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*Rsmrv5UfsdT2abKFXrvbqQ.png" /></figure><p>To express Jane’s coffee shop in code, we’ll create a few classes. The CoffeeGuru class is our vendor. It provides all the raw materials required to make coffee.</p><pre>class CoffeeGuru {<br>  getCoffeeBeans() {<br>    // Fetch the finest coffee beans<br>  }<br><br>  getWater() {<br>    // Retrieve purified water<br>  }<br><br>  getMilk() {<br>    // Procure fresh milk<br>  }<br>}</pre><p>The Barista class is responsible for actually making the coffee.</p><pre>class Barista {<br>  brewCoffee() {<br>     // ... makes amazing coffee<br>  }<br>}</pre><p>Finally, we create a CoffeeShop class to bring everything together. Let’s actually see how they all fit together.</p><pre>class CoffeeShop {<br>  constructor(barista) {<br>    this.barista = barista;<br>  }<br><br>  makeCappuccino() {<br>    return this.barista.brewCoffee();<br>  }<br>}</pre><h3>Harnessing the Power of Dependency Injection</h3><p>Jane uses CoffeeGuru to procure all the materials she requires so let’s use an instance of CoffeeGuru by “injecting” it into the Barista .</p><pre>class Barista {<br>  constructor(coffeeGuru) {<br>    this.ingredientProvider = coffeeGuru;<br>  }<br><br>  brewCoffee() {<br>    // ...<br>  }<br>}</pre><p>In code, injection means constructing the class with an instance of CoffeeGuru . This is known as <em>constructor injection</em>. There are other forms of injection such as <em>method injection</em> and <em>property injection </em>but the easiest and most widely used is <em>constructor injection</em>.</p><p>As simple as that! Let’s prepare some hot, piping cappuccino!</p><p>We’ll update our Barista so they can use all the wonderful beans and milk and other ingredients from CoffeeGuru</p><pre>class Barista {<br>  constructor(coffeeGuru) {<br>    this.ingredientProvider = coffeeGuru;<br>  }<br><br>  brewCoffee() {<br>    const coffeeBeans = this.ingredientProvider.getCoffeeBeans();<br>    const water = this.ingredientProvider.getWater();<br>    const milk = this.ingredientProvider.getMilk();<br><br>    // Brew the perfect cup of cappuccino using the ingredients<br>    // ...<br>  }<br>}</pre><h3>Bringing it all together</h3><p>Now that we have our vendor and barista all ready to go, we can start actually selling our coffee to customers.</p><p>We start by creating an instance CoffeeGuru . Next, we create an instance of Barista , injecting it with an instance of CoffeeGuru . Finally, we create our CoffeeShop and make it use (or inject) the Barista .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3dfmq0EBxgjZtxSMA5Wdw.png" /><figcaption>Bringing it all together in main.js</figcaption></figure><p>With the Coffee Guru’s expert guidance and the art of dependency injection, Jane can now serve her customers with the finest caffeine experience.</p><p>Phew! That was a LOT of work just to serve ☕️.</p><p>“Why go through all this hassle? 🤔”, you may wonder. Good question!</p><p>To see why this technique is so powerful, let’s say Jane decides her vendor is too expensive and she can no longer buy from them. In this contrived example, this change is simple. However, it showcases a very common occurrence in software development where things change frequently. For example, we decide to use Stripe over RazorPay for accepting customer payments, use raw SQL instead of an ORM to perform database queries etc...</p><p>You will very soon realise, dealing with all this without DI becomes untenable. Software, as opposed to hardware, is meant to be easily changeable. Hence the name. DI is one of the techniques that allows software to be… “soft”</p><p>To deal with a change in vendor, all we would need to do is create another class, say CoffeeCo , and use that instead of CoffeeGuru .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzNakzOOfGXyprLcgUocoQ.png" /></figure><p>By doing so, we only needed to change the vendor and nothing about the coffee making process needed to change! Awesome right!?🔥</p><h3>Let’s do a quick refactor</h3><p>The astute amongst you would have noticed I named the variable this.ingredientProvider in the Baristaclass instead of this.coffeeGuru .</p><pre>class Barista {<br>  constructor(coffeeGuru) {<br>    this.ingredientProvider = coffeeGuru;<br>  }<br>  <br>  brewCoffee() {<br>    const coffeeBeans = this.ingredientProvider.getCoffeeBeans();<br>    const water = this.ingredientProvider.getWater();<br>    const milk = this.ingredientProvider.getMilk();<br>    // Brew the perfect cup of cappuccino using the ingredients<br>    // ...<br>  }<br>}</pre><p>Since Barista doesn’t really care about which exact vendor provides the beans, naming our variable this way allows us to reference the provider in a more abstract form rather than using this.coffeeGuru as the vendor may change in the future. We can now update our Barista class like so:</p><pre>class Barista {<br>  constructor(ingredientProvider) {<br>    this.ingredientProvider = ingredientProvider;<br>  }<br>  <br>  brewCoffee() {<br>    const coffeeBeans = this.ingredientProvider.getCoffeeBeans();<br>    const water = this.ingredientProvider.getWater();<br>    const milk = this.ingredientProvider.getMilk();<br>    // Brew the perfect cup of cappuccino using the ingredients<br>    // ...<br>  }<br>}</pre><p>This change is minor and doesn’t affect the functionality of the Barista class. However, since <strong>code is read more than it is written</strong>, this enhances intent, as the dependency ingredientProvider clearly states that the Barista needs a vendor to provide ingredients but doesn’t care about a specific vendor such as CoffeeGuru .</p><p>If you would like to understand further about how dependency injection helps with maintaining and testing code, subscribe to get notified of my next post where I talk about exactly this concept.</p><p>If you liked this article and you learned something, don’t be shy… show some love with a 👏 . It really helps me reach a wider audience and motivates me to write more useful articles. 🙌🏻</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab3eafdedfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secret Weapon for Serverless Developers]]></title>
            <link>https://vijay-rangan.medium.com/boost-your-productivity-with-aws-step-functions-1934919447a3?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1934919447a3</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Tue, 16 May 2023 10:14:05 GMT</pubDate>
            <atom:updated>2023-05-30T19:18:22.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAb9jhz9k9ICQ9IFCIO-bw.jpeg" /></figure><h3>AWS Step Functions: The Secret Weapon for Serverless Developers</h3><p>In this post I’ll walk you through on how to use Step Functions (with an example) for the most common tasks, while giving a quick overview of JSONPath.</p><h3>Overview</h3><p>AWS Step Functions is a service that allows you to model complex workflows with little to no code. It is a state machine and uses a special language syntax call ASL or <strong>A</strong>mazon <strong>S</strong>tates <strong>L</strong>anguage to define states.</p><p>ASL allows you define <strong>Task</strong>s that make up the state machine. Further, ASL allows you to define transition between these states. For example, make a call to a web service and if the response is successful, store the data in DynamoDB, otherwise log to CloudWatch logs.</p><h3>JSONPath</h3><p>One of the tricky parts of working with ASL is it’s use of <strong>JSONPath</strong>. If you’re not already familiar, JSONPath is a query language for JSON much like XPath for XML. It allows you to select and extract data from a JSON document. You use a JSONPath expression to traverse the path to an element in the JSON structure.</p><p>Here’s a quick example. Say you have the following JSON response from an API call</p><pre>{<br>  &quot;pets&quot;: [<br>    {<br>      &quot;name&quot;: &quot;bruno&quot;,<br>      &quot;species&quot;: &quot;dog&quot;<br>    },<br>    {<br>      &quot;name&quot;: &quot;felix&quot;,<br>      &quot;species&quot;: &quot;cat&quot;<br>    }<br>  ]<br>}</pre><p>Say, you you want to get the name of the first pet, you would do so by using the JSONPath expression $.pets[0].name. $ is used to denote the root of the JSON document.</p><p>If you wanted to get the names of all the pets and ignore the other attributes you could do so by using the JSONPath expression $.pets[*].name . This would return [“bruno”, “felix&quot;]. Simple, right? Don’t worry, you’ll get a hang of it as you use it more.</p><p>We’ll focus on the 80% use-case to get productive with Step Functions and not get too into the weeds of JSONPath itself.</p><blockquote>JSONPath allows you to select and extract data from a JSON document</blockquote><h3>Diving In!</h3><p>With that prelude out of the way, let’s dive in!</p><p>Like most of software engineering, the most effective way to understand a concept is with a concrete example. A client of mine needed a way to easily extract data from a document uploaded by a user. This document is a government issued document like a passport.</p><p>Here is the state machine definition using ASL.</p><pre>{<br>  &quot;StartAt&quot;: &quot;FetchDocumentReference&quot;,<br>  &quot;States&quot;: {<br>    &quot;FetchDocumentReference&quot;: {<br>      &quot;Next&quot;: &quot;ExtractData&quot;,<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;ResultPath&quot;: &quot;$.document&quot;,<br>      &quot;ResultSelector&quot;: {<br>        &quot;Item.$&quot;: &quot;$.Item&quot;<br>      },<br>      &quot;Resource&quot;: &quot;arn:aws:states:::dynamodb:getItem&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;Key&quot;: {<br>          &quot;id&quot;: {<br>            &quot;S.$&quot;: &quot;$.docId&quot;<br>          }<br>        },<br>        &quot;TableName&quot;: &quot;DocumentTable&quot;,<br>        &quot;ConsistentRead&quot;: false<br>      }<br>    },<br>    &quot;ExtractData&quot;: {<br>      &quot;Next&quot;: &quot;SaveExtractedData&quot;,<br>      &quot;Retry&quot;: [<br>        {<br>          &quot;ErrorEquals&quot;: [<br>            &quot;Lambda.ServiceException&quot;,<br>            &quot;Lambda.AWSLambdaException&quot;,<br>            &quot;Lambda.SdkClientException&quot;<br>          ],<br>          &quot;IntervalSeconds&quot;: 2,<br>          &quot;MaxAttempts&quot;: 6,<br>          &quot;BackoffRate&quot;: 2<br>        }<br>      ],<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;ResultPath&quot;: &quot;$.extractedData&quot;,<br>      &quot;ResultSelector&quot;: {<br>        &quot;data.$&quot;: &quot;$.Payload.body&quot;<br>      },<br>      &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;FunctionName&quot;: &quot;arn:aws:lambda:us-east-1:123456789001:function:ExtractData&quot;,<br>        &quot;Payload.$&quot;: &quot;$.document.Item&quot;<br>      }<br>    },<br>    &quot;SaveExtractedData&quot;: {<br>      &quot;Next&quot;: &quot;TransformOutput&quot;,<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;ResultPath&quot;: &quot;$.savedExtractedData&quot;,<br>      &quot;ResultSelector&quot;: {<br>        &quot;Item.$&quot;: &quot;$.Attributes&quot;<br>      },<br>      &quot;Resource&quot;: &quot;arn:aws:states:::dynamodb:updateItem&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;Key&quot;: {<br>          &quot;id&quot;: {<br>            &quot;S.$&quot;: &quot;$.docId&quot;<br>          }<br>        },<br>        &quot;TableName&quot;: &quot;DocumentTable&quot;,<br>        &quot;ExpressionAttributeValues&quot;: {<br>          &quot;:val&quot;: {<br>            &quot;S.$&quot;: &quot;$.extractedData.data&quot;<br>          }<br>        },<br>        &quot;ReturnValues&quot;: &quot;ALL_NEW&quot;,<br>        &quot;UpdateExpression&quot;: &quot;set extractedData = :val&quot;<br>      }<br>    },<br>    &quot;TransformOutput&quot;: {<br>      &quot;Type&quot;: &quot;Pass&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;result.$&quot;: &quot;$.extractedData&quot;<br>      },<br>      &quot;OutputPath&quot;: &quot;$&quot;,<br>      &quot;End&quot;: true<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*-2euS7ZznyBD206rD5WUKw.png" /><figcaption>State Machine Graph</figcaption></figure><p>If that looks intimidating, don’t worry. Once you read through it, you’ll see that it’s really quite simple. Like any language, it has it’s own unique syntax that takes a minute to get used to.</p><p>So what does this state machine do?</p><h3>Application Flow</h3><p>This application allows users to upload a document to AWS S3. Once uploaded, a reference to the S3 object is stored in DynamoDB. Then, an event is fired that kicks off our state machine.</p><p>When the state machine is started, it’s input is as follows. We’ll refer to this as the “input” or “state” from here on.</p><pre>{<br>  &quot;docId&quot;: &quot;some-document-id&quot;<br>}</pre><h3>Step 1 : Fetch from DynamoDB</h3><p>Let’s zoom in and look at the first step. It gets the “row” from DynamoDB using the docId from the input. Here’s the task definition for this step:</p><pre>{<br>  &quot;FetchDocumentReference&quot;: {<br>    &quot;Next&quot;: &quot;ExtractData&quot;,<br>    &quot;Type&quot;: &quot;Task&quot;,<br>    &quot;ResultPath&quot;: &quot;$.document&quot;,<br>    &quot;ResultSelector&quot;: {<br>      &quot;Item.$&quot;: &quot;$.Item&quot;<br>    },<br>    &quot;Resource&quot;: &quot;arn:aws:states:::dynamodb:getItem&quot;,<br>    &quot;Parameters&quot;: {<br>      &quot;Key&quot;: {<br>        &quot;id&quot;: {<br>          &quot;S.$&quot;: &quot;$.docId&quot;<br>        }<br>      },<br>      &quot;TableName&quot;: &quot;DocumentTable&quot;,<br>      &quot;ConsistentRead&quot;: false<br>    }<br>  }<br>}</pre><p>This defines a step of Type: &quot;Task&quot; which is configured to fetch a document from DynamoDB. Notice there’s no call to Lambda or anything. This step does all the heavy lifting of reaching out to DynamoDB and performing the necessary query. This is defined in the block:</p><pre>{<br>  &quot;Resource&quot;: &quot;arn:aws:states:::dynamodb:getItem&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;Key&quot;: {<br>      &quot;id&quot;: {<br>        &quot;S.$&quot;: &quot;$.docId&quot;<br>      }<br>    },<br>    &quot;TableName&quot;: &quot;DocumentTable&quot;,<br>    &quot;ConsistentRead&quot;: false<br>  }<br>}</pre><p>If you’re wondering “What the hell is S.$: $.docId ?” 🤔 <br>Good question my astute reader! Let’s take a very small detour to understand why.</p><p>If you were to query DynamoDB, without JSONPath or Step Functions, your query would be something like like (using TypeScript).</p><pre>// ... imports etc. Left out for brevity<br>new GetItemCommand({<br>  TableName: &#39;foobar&#39;,<br>  Key: {<br>    id: {<br>      S: &#39;foobar&#39;<br>    },<br>  },<br>})</pre><p>This tells DynamoDB that the thing you’re looking up is of type String denoted by S and it has the value foobar. There are a few other types like M for Map , Nfor Number etc. We won’t go too deep into DynamoDB here, but you’re interested let me know in the comments and I’d be more than happy to get into detail in another post 👍🏻</p><p>… alrighty, back to the state machine.</p><p>Now that we know what Sis, what is S.$?<br>S.$ tells the state machine that the value is dynamic and that we’ll use a JSONPath expression to get it as opposed the a static value. If you remember from our little JSONPath tutorial earlier, $.docId means that we’re picking the docId field from the root of the input — denoted by $ .</p><p>If we don’t use S.$ the value that will be used is the literal String &quot;$.docId&quot; .<br>Kinda neat, right?</p><p>Lastly, the output of this task needs to go somewhere. That’s defined as follows</p><pre>{<br>  &quot;ResultPath&quot;: &quot;$.document&quot;,<br>  &quot;ResultSelector&quot;: {<br>    &quot;Item.$&quot;: &quot;$.Item&quot;<br>  },<br>}</pre><p>ResultPath tells Step Functions to append the result to the input (as opposed to OutputPath , which we’ll look at shortly). This adds a key called document to the root of the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAb9jhz9k9ICQ9IFCIO-bw.jpeg" /></figure><p>ResultSelector tells Step Functions what to select from the output of the operation (dynamodb:getItem). If you don’t specify this, the entirety of the output will be put in $.document<br>DynamoDB returns a lot of data — read capacity, http metadata etc. — which we don’t need. ResultSelector allows us to, well, select parts of that result (starting to become quite intuitive with context, huh 😁) and trim out the rest.</p><p>Like before, Item.$ tells Step Functions to get data from DynamoDB query using JSONPath — $.Item is a JSONPath expression that works on the result from DynamoDB and <strong>not </strong>the input.</p><p>Here’s what the input looks like after this step.</p><pre>{<br>  &quot;docId&quot;: &quot;some-document-id&quot;,<br>  &quot;document&quot;: {<br>    &quot;Item&quot;: {<br>      // ...<br>    }<br>  }<br>}</pre><h3>Step 2: Extract Data with Lambda</h3><p>At this point the document reference from DynamoDB (DDB) has been retrieved and the data is stored as part of the input under $.document.Item .</p><p>In this step we’ll call a lambda function with this data. We won’t look at the details of the lambda itself, as it is outside the scope of this artice. Here’s how the lambda is called from Step Functions</p><pre>{<br>  // ...<br>  &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;FunctionName&quot;: &quot;arn:aws:lambda:us-east-1:123456789001:function:ExtractData&quot;,<br>    &quot;Payload.$&quot;: &quot;$.document.Item&quot;<br>  }<br>  // ...<br>}</pre><p>Pretty straightforward, right? We’re calling an AWS Lambda using the ARN (Amazon Resource Name).<br>Payload.$ tells Step Functions to call the Lambda with a JSON object with the key Payload , populated with data from our state machine input — $.document.Item . Easy peasy 👏🏻</p><p>Where does the output from the lambda go? Let’s see!</p><pre>{<br>  // ...<br>  &quot;ResultPath&quot;: &quot;$.extractedData&quot;,<br>  &quot;ResultSelector&quot;: {<br>    &quot;data.$&quot;: &quot;$.Payload.body&quot;<br>  }<br>  // ...<br>}</pre><p>This tells Step Functions, like before, to append to the input of our state machine. Here we see ResultSelector again that tells Step Functions to select the body from the lambda response and place it inside the data key.</p><p><em>Note: In the </em><em>ResultSelector , </em><em>$.Payload is part of the Lambda response element and not from function code written by us. You can find a full reference below at the official documentation</em></p><p><a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-lambda.html">https://docs.aws.amazon.com/step-functions/latest/dg/connect-lambda.html</a></p><p>Here’s what the input looks like after this step</p><pre>{<br>  &quot;docId&quot;: &quot;some-document-id&quot;,<br>  &quot;document&quot;: {<br>    &quot;Item&quot;: {<br>      // ...<br>    }<br>  },<br>  &quot;extractedData&quot;: {<br>    &quot;data&quot;: {<br>      // ...<br>    }<br>  }<br>}</pre><h3><strong>Step 4: Transformation</strong></h3><p>Before you say anything… no, that wasn’t a typo 😁 The step — SaveExtractedData — pretty much follows the same pattern of working with DynamoDB. So let’s skip that for now and look at something new!</p><pre>{<br>  // ...<br>  &quot;TransformOutput&quot;: {<br>    &quot;Type&quot;: &quot;Pass&quot;,<br>    &quot;Parameters&quot;: {<br>      &quot;result.$&quot;: &quot;$.extractedData&quot;<br>    },<br>    &quot;OutputPath&quot;: &quot;$&quot;,<br>    &quot;End&quot;: true<br>  }<br>  // ...<br>}</pre><p>This one’s really interesting and I didn’t know it existed until I happened upon it in the docs.</p><p>Type: &quot;Pass&quot; is used to pass inputs to outputs without performing work such as calling a lambda function or querying DynamoDB. It is usually used for debugging your state machine but I chose to use it to transform the output of the entire flow.</p><p>Unlike what we’ve used so far, this task uses OutputPath as opposed to ResultPath . While ResultPath appends data to the input (or state), OutputPath replaces the input. Here we place the extractedData from our state — $.extractedData — and place it inside $.result .</p><p>Here’s what our final state looks like after this step</p><pre>{<br>  &quot;result&quot;: {<br>    // ... the extracted data<br>  }<br>}</pre><h3>Summary</h3><p>Here’s a quick look at what you learned today.</p><ul><li>$ — Root of JSON object. Returns all data in the JSON document.</li><li>$.someArray[0] — Returns the first item in the array.</li><li>$.someArray[*] — Returns all items in the array.</li><li>SomeKey.$: $.SomeOtherKey — A way to dynamically add keys with value from a JSONPath expression.</li><li>ResultPath — Append data to the state (or input) of the state machine.</li><li>OutputPath — Replace the data in the state (or input) of the state machine.</li><li>ResultSelector — Extract data from the result of an operation.</li></ul><p>Thank you so much for taking the time to read this article. This was something that I struggled with when I first started and I hope this article made the process of working with Step Functions easier.</p><p>If you liked it, I’d really appreciate a 👏🏻 or a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1934919447a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stubbing with Sinon in 5 mins]]></title>
            <link>https://vijay-rangan.medium.com/stubbing-with-sinon-in-5-mins-5c7b2af6123?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c7b2af6123</guid>
            <category><![CDATA[sinonjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[stub]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 19:01:43 GMT</pubDate>
            <atom:updated>2021-05-01T04:41:57.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vr8972w-u73HUj2EV750KA.jpeg" /></figure><p>Sinon is a library that provides fakes, spies, stubs and mocks (collectively called fakes) — each of which have their place in testing. We’re going to focus on stubs in this post, covering :</p><ol><li>What stubs are</li><li>How to use them to create stub objects</li><li>How to stub a single function</li><li>Sinon Sandbox</li></ol><h3>What is a Stub ?</h3><p>So first off, what is a stub ?</p><p>Simply, a stub allows us to change and set expectations on a function or property. To quote Linus Torvalds - “Talk is cheap, show me the code”.</p><p>Say we have a module — a user repository — that’s responsible for interacting with the users table in a database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPwFHJpudMK6LlPbQOdaMg.png" /></figure><p>And say we have a service that uses this module to do its job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LskXC_RBHhzZ2HIZ2HNOWg.png" /></figure><p>The user service takes an implementation of the user repository as a dependency, injected as an argument to the function. To unit test the service without actually spinning up a database (for the user repository), we need to create a stub.</p><p>Let’s look at how Sinon stubs work and how they aid in unit testing the user service module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2atV5Ta75GilO1vsX8XEjg.png" /></figure><p>Digging into each of the steps above :</p><pre>const stubbedUserRepo = sinon.stub(userRepo);</pre><p>This creates a stub (or a programmable object) of all the methods in the userRepo object whose behaviour we can change to suit our testing needs.</p><p>With this stubbed object, we tell the all method to return a list of user objects (just one in this case) when called.</p><pre>stubbedUserRepo.all.returns([{ <br>  id: 1, <br>  user: &quot;John Doe&quot;, <br>  email: &quot;<a href="/service/mailto:john@doe.com">john@doe.com</a>&quot; <br>}]);</pre><p>Calling the userRepo.all() returns a list of users.</p><pre>// programming the behaviour of the user repo<br>stubbedUserRepo.all.returns([{ <br>  id: 1, <br>  user: &quot;John Doe&quot;, <br>  email: &quot;<a href="/service/mailto:john@doe.com">john@doe.com</a>&quot; <br>}]);</pre><pre>// prints the object from above<br>console.log(userRepo.all());</pre><p>Apart from just returning values, stubs can resolve values too for promise based interfaces. They also allows us to specify error cases by using stub.throws for instances where we’d like to fake an error. For the full list of capabilities provided by Sinon stubs, check out the link below.</p><p>Sinon stub docs : <a href="https://sinonjs.org/releases/v10.0.1/stubs/">https://sinonjs.org/releases/v10.0.1/stubs/</a></p><h3>Stubbing a single function</h3><p>In some cases it may be beneficial to stub just a single method instead of an entire object. The sinon.stub function takes a second argument that specifies a the name of the function to stub.</p><pre>const registerUserStub = sinon.stub(userRepository, &#39;registerUser&#39;);</pre><p>This approach is useful if you have an object with just a few methods in it. Additionally, this approach conveys intent more explicitly.</p><h3>Restoring the user repository</h3><p>Say we had more tests that use this stub, we would need to restore the original userRepo object. This is because sinon mutates the original object and any tests that came after it would need to define it’s own behaviour. To restore the userRepo back to it’s original implementation :</p><pre>stubbedUserRepo.all.restore();</pre><p>Notice how we had to restore the method all specifically and couldn’t simply do stubberUserRepo.restore() . This approach can get cumbersome if you have an object with a lot of methods. To solve this, Sinon introduced sandboxes.</p><h3>Sandbox</h3><p>A sandbox, like the name suggests, creates a little playground of sorts. We can then use this sandbox to create a stub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-qyyJARG9laN21EZjjnMg.png" /></figure><p>Notice the call to sinon.createSandbox() . This returns a sandbox instance. We can now create stubs using this sandbox.</p><pre>userRepoSandbox.stub(userRepo); // instead of sinon.stub(userRepo)</pre><p>Using this approach, everything can remain the same but we now have the ability to restore the object as a whole rather than using a piecemeal approach with sinon.stub(...) .</p><pre>userRepoSandbox.restore();</pre><p>And that’s it! It’s literally that simple to work with stubs in JavaScript using Sinon.</p><p>If you’re the kind of person that likes consuming tech content via videos, you can find a video of this on my YouTube channel.</p><p>YouTube link : <a href="https://www.youtube.com/watch?v=VLe9LxyO6Qo">Learn how stubbing works in Sinon</a></p><p>If you liked this article and you learned something, don’t be shy… show some love with a 👏 😀</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c7b2af6123" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modelling Applications with JPA & Spring Boot]]></title>
            <link>https://vijay-rangan.medium.com/modelling-applications-with-jpa-spring-boot-8617e11b0e95?source=rss-ae0a1608778f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8617e11b0e95</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vijay Rangan]]></dc:creator>
            <pubDate>Wed, 24 Apr 2019 13:46:48 GMT</pubDate>
            <atom:updated>2019-04-24T13:58:22.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*98O4Gb5HLSlmdUkKg1DP1Q.png" /></figure><p><strong>A short prelude</strong></p><p>I recently attended a bootcamp where we needed to setup an API for an e-commerce store using Spring Boot. The API itself was fairly straightforward — a list of books that can be purchased and a cart to hold a bunch of books — your typical e-commerce application.</p><p>I, like most of my teammates during the bootcamp, were very new to Spring Boot and relied heavily on documentation to get up and running. Most of us came from rich ecosystems like Ruby on Rails, Laravel, Express etc… where setting up an API is a fairly quick task and the ORM generally is very quick to setup and start using.</p><p>Unfortunately, things aren’t that straight forward with Spring Boot. The go-to ORM when using Spring Boot, from my limited experience, is JPA. If you’ve done it long enough, you’re probably at home working with it, but since you’re reading this post, I presume you’re in a situation where you <strong>just can’t figure out</strong> how the pieces fit together.</p><p>This blog post, hopefully will give you an overview of accomplishing the most common tasks using JPA and Spring Boot -</p><ul><li>Creating Model classes</li><li>Customising model attributes (columns and tables)</li><li>Creating relationships between models (tables)</li></ul><p><strong>What is JPA</strong></p><p>JPA or Java Persistence API is a layer of abstraction for interacting with SQL databases. It is an ORM.</p><p><strong>Creating and Customising Models</strong></p><p>The basic unit of persistence in JPA is the <strong>Entity, </strong>which is nothing but a Java class with annotations. This class describes the database table. Every <strong>Entity</strong> class must have an @Entity annotation and @Id annotation, which maps to the primary key of the table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d67dcf2b8576201945941036c5a9ccb/href">https://medium.com/media/4d67dcf2b8576201945941036c5a9ccb/href</a></iframe><p>The @Table annotation is optional. By default, JPA will use the Java class name as the table name. In this case, my table name is books while my class is named Book</p><p>Similarly, let’s create a Customerentity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26278b77f1b9f9f997a0c934fa85f603/href">https://medium.com/media/26278b77f1b9f9f997a0c934fa85f603/href</a></iframe><p>Continuing with our e-commerce use case, we need to create an orderstable that will generate an order id and have a reference to the customer who placed the order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd5fe58bd5634e80f8c5abace97fd9e/href">https://medium.com/media/9fd5fe58bd5634e80f8c5abace97fd9e/href</a></iframe><p><strong>Relationships</strong></p><p>One of the major advantages SQL databases provide is relationships and integrity constraints. Our book store allows a customer to order many books. In our current schema, a customer can create an order but there is no table to hold the line items for that order. Since each order contains many line items we need to create a new table order_line_items that can hold this information. This is a one-to-many relationship where each order has many line items.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29b7dad31183799d883fe2fab8a39aff/href">https://medium.com/media/29b7dad31183799d883fe2fab8a39aff/href</a></iframe><p>A few new annotations are used:</p><ul><li>@Column is similar to @Table It allows us to break out of the default behaviour of JPA and specify a custom column name.</li><li>@ManyToOne is the glue that specifies the relationship between the two tables. This allows us to do lineItem.order.id in our code to fetch the related model.</li><li>@JoinColumn informs JPA about the column (foreign key) that is used to form this relationship in our table.</li></ul><p>Also, notice that we added 2 more properties to the class without any annotations — Double price and Double quantity. JPA, by default, will look for columns by this name.</p><p>Now that we have setup the @ManyToOne relationship, let’s do the inverse, ie create a @OneToMany relationship from Order entity to OrderLineItem. Additionally, we will define the relationship between aCustomer and Order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8dcc2f27a16511f6cf0f249d52e2d75/href">https://medium.com/media/c8dcc2f27a16511f6cf0f249d52e2d75/href</a></iframe><p>In a bidirectional relationship pair, such as the @OneToMany relationship fromOrder to OrderLineItem and the @ManyToOne relationship back from OrderLineItem to Order, only one foreign key is required in one of the entities to manage both sides of the relationship. As a general rule, the side that does not have the foreign key (in our case Order) specifies a mappedBy attribute in the relationship annotation and specifies the field in the related entity (in our case OrderLineItem) that maps the foreign key.</p><p>Finally, we’ll define the relationship from Customer to Order. We know that a customer can place multiple orders, so our relationship here is @OneToMany from Customer to Order</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e4b98d74454bd55dd1e9832066c2ae/href">https://medium.com/media/74e4b98d74454bd55dd1e9832066c2ae/href</a></iframe><p>And that’s it! With this, you should have the minimum setup required to get up and running using JPA as your ORM.</p><p>If this post helped you, I’d love a 👏</p><p>PS: If I made any mistakes please let me know in the comments. I’m new to Java and would love to better my understanding.</p><p>PPS: <a href="https://github.com/vjrngn/spring-boot-jpa-demo">Here’s the code!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8617e11b0e95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>