<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Posts on Jamie Corkhill</title>
        <link>/posts/</link>
        <description>Recent content in Posts on Jamie Corkhill</description>
        <generator>Hugo -- gohugo.io</generator>
        <language>en-us</language>
        <lastBuildDate>Sat, 27 Feb 2021 00:38:10 -0600</lastBuildDate>
        <atom:link href="/posts/index.xml" rel="self" type="application/rss+xml" />
        
        <item>
            <title>An Ever Growing Collection of Software Development Advice</title>
            <link>/2021/02/an-ever-growing-collection-of-software-development-advice/</link>
            <pubDate>Sat, 27 Feb 2021 00:38:10 -0600</pubDate>
            
            <guid>/2021/02/an-ever-growing-collection-of-software-development-advice/</guid>
            <description>This article marks the home of an ever growing list of random software development advice, mostly covering architecture, mannerisms, principals, and practices. It is updated regularly and you can see the Changelog at the bottom of this page for more details.
On Unit Testing Work in Progress.
On Language and Framework Superiority It&amp;rsquo;s rather pervasive, especially among members of the web development industry, to consider certain languages, frameworks, and libraries as supreme to others - in some cases going as far as to say that said language, framework, or library is the best in the world.</description>
            <content type="html"><![CDATA[<p>This article marks the home of an ever growing list of random software development advice, mostly covering architecture, mannerisms, principals, and practices. It is updated regularly and you can see the <a href="#changelog">Changelog</a> at the bottom of this page for more details.</p>
<h2 id="on-unit-testing">On Unit Testing</h2>
<p>Work in Progress.</p>
<!-- raw HTML omitted -->
<h2 id="on-language-and-framework-superiority">On Language and Framework Superiority</h2>
<p>It&rsquo;s rather pervasive, especially among members of the web development industry, to consider certain languages, frameworks, and libraries as supreme to others - in some cases going as far as to say that said language, framework, or library is the best in the world.</p>
<p>Such blanket statements are inherently erroneous and speak to the inexperience of the person making the statement.</p>
<p>At the end of the day, all languages, frameworks, libraries, principals, patterns, mechanisms, and architectures are <em>merely</em> <strong>tools</strong> - they exist solely as a means to an end, as a means to get the job done. Depending on the situation, one tool may be better suited than another to get that job done, but that never implies that said tool is in any manner &ldquo;supreme&rdquo; to the other(s) outside of that situation.</p>
<p>It&rsquo;s important to understand that everything exists within a given context - all that ever succeeded did so within a clearly defined context, and everything that ever failed did so within an equally clearly defined context. Pick the tools that best fit the context within which you wish to use them.</p>
<p>The specific criteria for tool selection that arise out of a given context aren&rsquo;t always strictly technical in nature - generally, political and logistical considerations have to be factored in, and it&rsquo;s up to you to decide how to balance the two. The priority of feature completion (time-to-market), the current skills and operating scope of the team, the performance requirements of the solution, the weight assigned to maintainability and the minimization of future technical debt, the community and ecosystem around the tech/tool, and more should go into deciding upon a specific tool, not the preference of the developer or development team.</p>
<p>This sounds rather quite obvious, and, alas, it probably is to most. With that said, I all-too-often see and hear people publicly declare their favorite technologies and tech stacks and state that they use them for every project or every requirement, which is asking for trouble.</p>
<p>Since I often hear this from some members of the web development community, I most generally see JavaScript, Node.js, and MongoDB held up to very high esteem and applied (erroneously) unilaterally across contexts. Just because you <em>can</em> use JavaScript on the front-end and the back-end doesn&rsquo;t mean you <em>should</em>. That said, it doesn&rsquo;t mean you <em>shouldn&rsquo;t</em> either - decide based on the context you&rsquo;re operating within. Similarly, just because there are methods of programming Microcontrollers with JavaScript doesn&rsquo;t imply that that&rsquo;s a good idea either - it just means the possibility exists. The same goes for MongoDB - most domains are inherently relational, and trying to represent such data in a denormalized manner won&rsquo;t always work out well (not that there aren&rsquo;t use cases for document storage forms - there are).</p>
<p>Additionally, undue hate, negativity, and insults toward technologies follow naturally (unfortunately) from the designation of other technologies as supreme. For instance, you most often hear people make fun of C#, Java, and PHP as being old, legacy, out of date, reserved only for enterprise use cases, and too hard to work with. None of this is true, and the hilarious thing is that many of the people who make such statements have likely never worked with any of these, and instead merely jump on the bandwagon. The fact of the matter is that C#, Java, and PHP are great languages, have their use cases, and <em>do their jobs very well</em>, just as JavaScript does its job well.</p>
<p>Just like you wouldn&rsquo;t attempt to use a Phillips screwdriver in all scenarios just because you &ldquo;prefer&rdquo; it to flatheads, don&rsquo;t try to utilize technologies in all situations either. <strong>If you have to massage the tool to fit the use case, then the tool isn&rsquo;t the right tool for the job.</strong> Let the needs of the project - both technical and political, your existing experience, the size and maturity of the community and the ecosystem around the tool, and any other relevant criteria govern technology selection. In doing so, you can make decisions through a purely objective lens.</p>
<h2 id="on-coding-against-interfaces-and-dependency-injection">On Coding Against Interfaces and Dependency Injection</h2>
<blockquote>
<p>This is a quick overview. To learn about Dependency Injection in full, see my article <a href="/2020/12/a-practical-introduction-to-dependency-injection/">A Practical Introduction to Dependency Injection</a>.</p>
</blockquote>
<p>&ldquo;Dependency Injection&rdquo; - it sounds complicated. Three natural questions arise - &ldquo;what&rsquo;s a dependency?&rdquo;, &ldquo;what does it mean for a dependency to be injected?&rdquo;, &ldquo;why would I want to inject a dependency?&rdquo;</p>
<p>If some class <code>A</code> relies on the functionality of a class <code>B</code>, then <code>B</code> is a dependency for <code>A</code>, or, in other words, <code>A</code> holds a dependency on <code>B</code>. Consider a <code>UserService</code> class using the functionality of an <code>EmailSender</code> class. In that case, <code>EmailSender</code> is a dependency for <code>UserService</code> - <code>UserService</code> <strong>depends on</strong> <code>EmailSender</code> to function correctly.</p>
<p>It&rsquo;s pretty clear that dependencies are not a rare thing. In fact, it&rsquo;s common for a class to have many dependencies, and that&rsquo;s not a bad thing (so long as relevant principles like SRP aren&rsquo;t violated). The problem, though, comes from how you manage those dependencies. The concept of a dependency introduces the idea of relationships between classes, and relationships can cause different levels of coupling. The two partners of <code>UserService</code> and <code>EmailSender</code> are collaborators - they collaborate together. How said collaborators collaborate determines how much an application will resist change and resist testing.</p>
<p>If <code>UserService</code> instantiates a new <code>EmailSender</code> in its constructor, then calling code for <code>UserService</code> has no control over how the <code>EmailSender</code> is managed, nor can it swap out the <code>EmailSender</code> for a different kind if the business migrates or for a fake in a test case. We can solve this high degree of coupling and invert control back to the caller by only permitting <code>UserService</code> to receive an instance of an <code>EmailSender</code> into its constructor instead, and not create the <code>EmailSender</code> itself.</p>
<p>This, then, answers the second question and third questions - passing an instance of a dependency into a constructor (or through function arguments, we don&rsquo;t have to restrict ourselves to classes) is what it means to inject that dependency, and the reason we do it is to reduce coupling and give control back to the caller.</p>
<p>The issue that probably comes to mind, at this moment, is if <code>UserService</code> expects the type of the injected dependency to be <code>EmailSender</code>, then we still have high coupling because it means we have to pass an <code>EmailSender</code> in. We can&rsquo;t pass in a <code>FakeEmailSender</code>. We&rsquo;ve solved the creation side of things - the lifetime management side, but not the fact the dependency remains too rigid through the type system. This is where interfaces come in.</p>
<p>Consider the notion of powering a toaster. You, the user, need not have any understanding of electronics to figure out how to run current through the toaster and heat the filament. Similarly, you need not worry about the max current that can be pulled through the socket, the voltage potential between live and neutral, what the frequency of the AC current is, what current draw over what time period will cause a breaker to trip, or even what the source of the electricity is.</p>
<p>Really, the only thing you&rsquo;re concerned about is inserting the plug into the outlet. If the plug doesn&rsquo;t fit, then you have a problem - maybe you&rsquo;re trying to use a European plug in a North American outlet and need an <em>adapter</em> (this is a design pattern), but, for the most part, the functionality is plug and play. The electricity source and the individual wires behind that outlet can change as much as it wants, but never will that affect your ability to place the toaster in the outlet so long as the outlet never changes. Another way to look at is you can swap the toaster for another toaster, a microwave, a kettle, or anything without the wall or wall wiring have to change. The outlet is the interface - it&rsquo;s agnostic to any concrete implementation of electricity or appliance, and it merely defines behavior (current flow) - not concretions, but <strong>behavior</strong>.</p>
<p>By defining an interface like <code>IEmailSender</code>, you&rsquo;re freed to create concrete implementations such as <code>SendGridEmailSender : IEmailSender</code> or <code>FakeEmailSender : IEmailSender</code> (that&rsquo;s <code>SendGridEmailSender implements IEmailSender</code> and <code>FakeEmailSender implements IEmailSender</code> for Java and TypeScript developers) that implement the interface. To implement the interface means to have the behavior as defined in the interface.</p>
<p>Interfaces can go hand in hand with Dependency Injection because now you can depend upon abstractions and not concretions. You can inject some email sender that honors the <code>IEmailSender</code> interface into <code>UserService</code>, and <code>UserService</code> doesn&rsquo;t need to know what it actually is because it knows what behavior is possible/provided thanks to the interface.</p>
<blockquote>
<p>This was a quick overview. To learn about Dependency Injection in full, see my article A Practical Introduction to Dependency Injection](/2020/12/a-practical-introduction-to-dependency-injection/).</p>
</blockquote>
<h2 id="on-language-proficiency-and-the-preservation-of-commonalities">On Language Proficiency and the Preservation of Commonalities</h2>
<p>Rather recently, I heard someone say that when working with various programming languages, they attempt to maintain and preserve commonalities - &ldquo;mannerisms&rdquo; - between those languages. For instance, they stick to classes as much as possible in JavaScript as to maintain a similar feel to Java and C#, and that this helps them easily move between languages rapidly.</p>
<p>This is an atrociously flawed mindset, the implications of which are fairly obvious. If you constrain yourself to utilizing the features shared across all languages, you effectively lock yourself to the least common denominator. There no longer becomes a reason to pick one programming language over another, for all will act just the same to you. The intersection of the set of features between languages will grow ever smaller with the more languages you attempt to add to the mix.</p>
<p>This idea of preserving commonalities is one that I can understand if coming from a new developer. They may not be viewing programming languages and technologies as <em>mere tools</em> quite yet, and they are likely moving between learning different languages with no clear direction, rhyme, or reason. This issue likely stems from a new programmer thinking that the more languages they add to their tool belt, the better a developer they become, when, in fact, the opposite is true. Learning only for the sake of learning, while not a bad thing in and of itself, tends to produce mindsets like these. Instead, a beginner should pick a language based on their interests, excel to a reasonable level of proficiency with that language, and then move on to a new one as required, taking advantage of the full scope of features that each language has to offer as they go.</p>
<p>I&rsquo;m certainly not saying that learning for the sake of learning is a bad thing, just that having a <em>reason to learn</em> often makes for an easier and more streamlined learning experience. But deciding to learn the basics of Java, then the basics of C#, and then the basics of JavaScript simply makes you a software developer who knows nothing of real substance about 3 different languages when you could instead aim to reach a level of relative proficiency in just one said language, the knowledge of which will be easily transferable to the other two when such a transfer is needed.</p>
<p>That last point is what makes mere surface-level knowledge across an array of languages nowhere near as valuable as proficient-level knowledge of one. With the exception of static and dynamic typing and functional programming, most languages are actually pretty similar to one another, thus even the advanced concepts of a language like C# will prove somewhat helpful if you need to learn Java or JavaScript. Asynchrony, for instance, is a generally language-agnostic concept that is, most unfortunately, often taught within the context of a specific one, but you won&rsquo;t hear about asynchrony if basic data structures and control flow is the limit to how far you get dividing your time across N languages. If you had stuck with only C#, knowledge of C#&rsquo;s asynchrony features would serve you well when making the move to JavaScript.</p>
<h2 id="changelog">Changelog</h2>
<p><strong>February 27, 2021 at 11:47 PM CDT (05:47 AM Zulu):</strong></p>
<ul>
<li>Added section <a href="#on-unit-testing">On Unit Testing</a>.</li>
<li>Added section <a href="#on-language-and-framework-superiority">On Language and Framework Superiority</a>.</li>
</ul>
<p><strong>March 3, 2021 at 12:03 AM CDT (06:04 AM Zulu):</strong></p>
<ul>
<li>Added section <a href="#on-coding-against-interfaces-and-dependency-injection">On Coding Against Interfaces and Dependency Injection</a>.</li>
<li>Added section <a href="#on-language-proficiency-and-the-preservation-of-commonalities">On Language Proficiency and the Preservation of Commonalities</a>.</li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>Comments Are Not Always an Anti-Pattern</title>
            <link>/2021/02/comments-are-not-always-an-anti-pattern/</link>
            <pubDate>Wed, 17 Feb 2021 11:57:10 -0600</pubDate>
            
            <guid>/2021/02/comments-are-not-always-an-anti-pattern/</guid>
            <description>It certainly would not be erroneous to state that, more often than not, feeling the need to write comments implies a problem with underlying design - that the code itself leaves something to be desired. Code should be expressive and interfaces should be intention-revealing. If you get this right, you rarely need comments. The notion of behavior, not mere data, should be treated as first-class.
It would make sense, then, to extrapolate this idea and say that comment usage itself is an anti-pattern.</description>
            <content type="html"><![CDATA[<p>It certainly would not be erroneous to state that, more often than not, feeling the need to write comments implies a problem with underlying design - that the code itself leaves something to be desired. Code should be expressive and interfaces should be intention-revealing. If you get this right, you rarely need comments. The notion of behavior, not mere data, should be treated as first-class.</p>
<p>It would make sense, then, to extrapolate this idea and say that comment usage itself is an anti-pattern. But that, for reasons which should be quite obvious, is undeniably false. In fact, <strong>the <em>biggest</em> anti-pattern of all is believing that some statement or idea applies to all situations unilaterally, without exception, and without limitation.</strong></p>
<p>While it is true that comments have the risk of becoming stale over time and need to be maintained along with the code, there are, in fact, I believe, a multitude of situations where comment usage is justified, primarily because comments excel greatly at providing information that is not expressible in code.</p>
<h3 id="sacrifices-for-performance">Sacrifices for Performance</h3>
<p>There may be small, rare cases where the performance requirements of an application dictate that readability must be sacrificed to maintain adequate perf. In such cases, comment usage is justified. Indeed, readability should seldom be sacrificed, but at the end of the day, design requirements must be fulfilled. You could have beautifully written and elegant code, but if the system doesn&rsquo;t work as needed, or if it doesn&rsquo;t function at the performance level expected, what&rsquo;s the point?</p>
<h3 id="workarounds">Workarounds</h3>
<p>There are generally cases where one has to take seemingly unjustified actions in code to work around a bug or handle an edge case. It is crucial that this be well documented, thus comment usage is justified (and required), perhaps even linking to relevant issue numbers, if any.</p>
<h3 id="english-explanations">English Explanations</h3>
<p>Certain operations may benefit from English explanations - especially paradigms that not all developers are aware of. Functional Reactive Programming, for instance, where the dimension of time is implicit and all data is streamed, might benefit from a brief explanation. With that said, such an explanation need not be first-class in code, but a small one here and there doesn&rsquo;t necessarily imply issues with expressiveness. If anything, it adds to it. Concepts like these aren&rsquo;t always intuitive, can&rsquo;t always be understood no matter how expressive and intension-revealing the code might be (especially if they&rsquo;re fundamentally implicit, perhaps even philosophical in nature), and a comment is a small price to pay to avoid confusion.</p>
<p>A need for English explanations may also arise out of situations where code is performing operations that are heavily algorithmic or mathematical in nature, such as graphics, audio analysis/FFT, physics, etc. Namely, concepts beyond the scope of most developers who aren&rsquo;t specialized in the domain.</p>
<h2 id="when-comment-usage-isnt-justified--why-reliance-should-be-placed-on-tests">When Comment Usage isn&rsquo;t Justified &amp; Why Reliance Should be Placed on Tests</h2>
<p>In almost all other cases, comment usage does indeed imply that code should be refactored to express the meaning that once only existed within the comment. During refactoring, the meaning once implied in comments should manifest itself within the code based on proper naming, emphasis on behavior, the Tell Don&rsquo;t Ask principle, and, crucially, unit tests.</p>
<p>Saying that a unit test only exists to validate a given behavior is equally erroneous as stating that comments are always an anti-pattern. There is another crucial piece of value provided by tests that isn&rsquo;t always taken advantage of - not only do they verify behavior, they tell stories, they provide insight into logic and the domain.</p>
<p>Test suites should be written such that a developer can gain all the insight he or she needs into the codebase by reading the story that the tests tell, be that through scenarios like Given/When/Then or Arrange/Act/Assert. Writing expressive code in the first place plus having expressive test suites to fill in the gaps should remove both ambiguity and the need for comments entirely except in those cases listed above. Heavy procedural flows generally attract comments, for instance, when they can be perfectly explained in tests.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Everything is situational. Use comments when comments will add value. That&rsquo;s it. But don&rsquo;t use them in lieu of or as an excuse for going without expressive code and expressive test suites.</p>
]]></content>
        </item>
        
        <item>
            <title>A Practical Introduction to Dependency Injection</title>
            <link>/2020/12/a-practical-introduction-to-dependency-injection/</link>
            <pubDate>Wed, 30 Dec 2020 21:25:12 -0600</pubDate>
            
            <guid>/2020/12/a-practical-introduction-to-dependency-injection/</guid>
            <description>This article was first written for Smashing Magazine on December 30, 2020. You can find it here.
Introduction The concept of Dependency Injection is, at its core, a fundamentally simple notion. It is, however, commonly presented in a manner alongside the more theoretical concepts of Inversion of Control, Dependency Inversion, the SOLID Principles, and so forth. To make it as easy as possible for you to get started using Dependency Injection and begin reaping its benefits, this article will remain very much on the practical side of the story, depicting examples that show precisely the benefits of its use, in a manner chiefly divorced from the associated theory.</description>
            <content type="html"><![CDATA[<blockquote>
<p>This article was first written for Smashing Magazine on December 30, 2020. You can find it <a href="https://www.smashingmagazine.com/2020/12/practical-introduction-dependency-injection/">here</a>.</p>
</blockquote>
<h3 id="introduction">Introduction</h3>
<p>The concept of Dependency Injection is, at its core, a fundamentally simple notion. It is, however, commonly presented in a manner alongside the more theoretical concepts of Inversion of Control, Dependency Inversion, the SOLID Principles, and so forth. To make it as easy as possible for you to get started using Dependency Injection and begin reaping its benefits, this article will remain very much on the practical side of the story, depicting examples that show precisely the benefits of its use, in a manner chiefly divorced from the associated theory. We&rsquo;ll spend only a very little amount of time discussing the academic concepts that surround dependency injection here, for the bulk of that explanation will be reserved for the second article of this series. Indeed, entire books can be and have been written that provide a more in-depth and rigorous treatment of the concepts.</p>
<p>Here, we&rsquo;ll start with a simple explanation, move to a few more real-world examples, and then discuss some background information. Another article, to follow this one, will discuss how Dependency Injection fits into the overall ecosystem of applying best-practice architectural patterns.</p>
<h3 id="a-simple-explanation">A Simple Explanation</h3>
<p>&ldquo;Dependency Injection&rdquo; is an overly-complex term for an extremely simple concept. At this point, some wise and reasonable questions would be &ldquo;how do you define &ldquo;dependency&rdquo;?&rdquo;, &ldquo;what does it mean for a dependency to be &ldquo;injected&rdquo;?&rdquo;, &ldquo;can you inject dependencies in different ways?&rdquo;, &ldquo;why is this useful?&rdquo; You might not believe that a term like &ldquo;Dependency Injection&rdquo; can be explained in two code snippets and a couple of words, but alas, it can:</p>
<p>The simplest way to explain the concept is to show you. This is <strong>not</strong> dependency injection:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">Engine</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./Engine&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Car</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">engine</span>: <span style="color:#66d9ef">Engine</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> () {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">engine</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Engine</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">startEngine</span>()<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">engine</span>.<span style="color:#a6e22e">fireCylinders</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>And this <strong>is</strong> dependency injection:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">Engine</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./Engine&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Car</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">engine</span>: <span style="color:#66d9ef">Engine</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">engine</span>: <span style="color:#66d9ef">Engine</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">engine</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">engine</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">startEngine</span>()<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">engine</span>.<span style="color:#a6e22e">fireCylinders</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Done. That&rsquo;s it. Cool. The end.</p>
<p>What changed? Rather than allow the <code>Car</code> class to instantiate <code>Engine</code>, as it did in the first example, in the second example, <code>Car</code> had an instance of <code>Engine</code> passed in, or <em>injected</em> in, from some higher level of control, to its constructor. That&rsquo;s it. At its core, this is all dependency injection is - the act of injecting (passing) a dependency into another class or function. Anything else involving the notion of dependency injection is simply a variation on this fundamental and simple concept. Put trivially, dependency injection is a technique whereby an object receives other objects it depends on, called dependencies, rather than creating them itself.</p>
<p>In general, to define what a &ldquo;dependency&rdquo; is, if some class <code>A</code> uses the functionality of a class <code>B</code>, then <code>B</code> is a dependency for <code>A</code>, or, in other words, <code>A</code> has a dependency on <code>B</code>. Of course, this isn&rsquo;t limited to classes and holds for functions too. In this case, the class <code>Car</code> has a dependency on the <code>Engine</code> class, or <code>Engine</code> is a dependency of <code>Car</code>. Dependencies are simply variables, just like most things in programming.</p>
<p>Dependency Injection is widely-used to support many use cases, but perhaps the most blatant of uses is to permit easier testing. In the first example, we can&rsquo;t easily mock out <code>engine</code> because the <code>Car</code> class instantiates it. The real engine is always being used. But, in the latter case, we have control over the <code>Engine</code> that is used, which means, in a test, we can subclass <code>Engine</code> and override its methods. For example, if we wanted to see what <code>Car.startEngine()</code> does if <code>engine.fireCylinders()</code> throws an error, we could simply create a <code>FakeEngine</code> class, have it extend the <code>Engine</code> class, and then override <code>fireCylinders</code> to make it throw an error. In the test, we can inject that <code>FakeEngine</code> object into the constructor for <code>Car</code>. Since <code>FakeEngine</code> <strong>is an</strong> <code>Engine</code> by implication of inheritance, the TypeScript type system is satisfied.</p>
<p>I want to make it very, very clear that what you see above is the core notion of dependency injection. A <code>Car</code>, by itself, is not smart enough to know what engine it needs. Only the engineers that <em>construct</em> the car understand the requirements for its engines and wheels. Thus, it makes sense that the people who <em>construct</em> the car provide the specific engine required, rather than letting a <code>Car</code> itself pick whichever engine it wants to use. I use the word &ldquo;construct&rdquo; specifically because you construct the car by calling the constructor, which is the place dependencies are injected. If the car also created its own tires in addition to the engine, how do we know that the tires being used are safe to be spun at the max RPM the engine can output? For all these reasons and more, it should make sense, perhaps intuitively, that <code>Car</code> should have nothing to do with deciding what <code>Engine</code> and what <code>Wheels</code> it uses. They should be provided from some higher level of control. In the latter example depicting dependency injection in action, if you imagine <code>Engine</code> to be an abstract class rather than a concrete one, this should make even more sense - the car knows it needs an engine and it knows the engine has to have some basic functionality, but how that engine is managed and what the specific implementation of it is is reserved for being decided and provided by the piece of code that creates (constructs) the car.</p>
<h3 id="a-real-world-example">A Real-World Example</h3>
<p>We&rsquo;re going to look at a few more practical examples that hopefully help to explain, again intuitively, why dependency injection is useful. Hopefully, by not harping on the theoretical and instead moving straight into applicable concepts, you can more fully see the benefits that dependency injection provides, and the difficulties of life without it. We&rsquo;ll revert to a slightly more &ldquo;academic&rdquo; treatment of the topic later.</p>
<p>We&rsquo;ll start by constructing our application normally, in a manner highly coupled, without utilizing dependency injection or abstractions, so that we come to see the downsides of this approach and the difficulty it adds to testing. Along the way, we&rsquo;ll gradually refactor until we rectify all of the issues.</p>
<p>To begin, suppose you&rsquo;ve been tasked with building two classes - an email provider and a class for a data access layer that needs to be used by some <code>UserService</code>. We&rsquo;ll start with data access, but both are easily defined:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// UserRepository.ts
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">dbDriver</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;pg-driver&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>: <span style="color:#66d9ef">User</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... dbDriver.save(...)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... dbDriver.query(...)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">email</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... dbDriver.save(...)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><em><strong>Note:</strong> The name &ldquo;Repository&rdquo; here comes from the &ldquo;Repository Pattern&rdquo;, a method of decoupling your database from your business logic. You can <a href="https://martinfowler.com/eaaCatalog/repository.html">learn more about the Repository Pattern</a>, but for the purposes of this article, you can simply consider it to be some class that encapsulates away your database so that, to business logic, your data storage system is treated as merely an in-memory collection. Explaining the Repository Pattern fully is outside the purview of this article.</em></p>
<p>This is how we normally expect things to work, and <code>dbDriver</code> is hardcoded within the file.</p>
<p>In your <code>UserService</code>, you&rsquo;d import the class, instantiate it, and start using it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">UserRepository</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./UserRepository.ts&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserService</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">UserRepository</span>;
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> () {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Not dependency injection.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">UserRepository</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">dto</span>: <span style="color:#66d9ef">IRegisterUserDto</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// User object &amp; validation
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">dto</span>.<span style="color:#a6e22e">email</span>))
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">DuplicateEmailError</span>());
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Database persistence
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Send a welcome email
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// No need for await here, the promise will be unwrapped by the caller.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Once again, all remains normal.</p>
<p><em><strong>A brief aside:</strong> A DTO is a Data Transfer Object - it&rsquo;s an object that acts as a property bag to define a standardized data shape as it moves between two external systems or two layers of an application. You can learn more about DTOs from Martin Fowler&rsquo;s article on the topic, <a href="https://martinfowler.com/eaaCatalog/dataTransferObject.html">here</a>. In this case, <code>IRegisterUserDto</code> defines a contract for what the shape of data should be as it comes up from the client. I only have it contain two properties - <code>id</code> and <code>email</code>. You might think it&rsquo;s peculiar that the DTO we expect from the client to create a new user contains the user&rsquo;s ID even though we haven&rsquo;t created a user yet. The ID is a UUID and I allow the client to generate it for a variety of reasons, which are outside the scope of this article. Additionally, the <code>findUserById</code> function should map the <code>User</code> object to a response DTO, but I neglected that for brevity. Finally, in the real world, I wouldn&rsquo;t have a <code>User</code> domain model contain a <code>fromDto</code> method. That&rsquo;s not good for domain purity. Once again, its purpose is brevity here.</em></p>
<p>Next, you want to handle the sending of emails. Once again, as normal, you can simply create an email provider class and import it into your <code>UserService</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// SendGridEmailProvider.ts
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">sendMail</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;sendgrid&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">SendGridEmailProvider</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">to</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... await sendMail(...);
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Within <code>UserService</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">UserRepository</span> }  <span style="color:#66d9ef">from</span>  <span style="color:#e6db74">&#39;./UserRepository.ts&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">SendGridEmailProvider</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./SendGridEmailProvider.ts&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserService</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">UserRepository</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">sendGridEmailProvider</span>: <span style="color:#66d9ef">SendGridEmailProvider</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> () {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Still not doing dependency injection.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">UserRepository</span>();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">sendGridEmailProvider</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">SendGridEmailProvider</span>();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">dto</span>: <span style="color:#66d9ef">IRegisterUserDto</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// User object &amp; validation
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">dto</span>.<span style="color:#a6e22e">email</span>))
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">DuplicateEmailError</span>());
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Database persistence
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Send welcome email
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">sendGridEmailProvider</span>.<span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">email</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>We now have a fully working class, and in a world where we don&rsquo;t care about testability or writing clean code by any manner of the definition at all, and in a world where technical debt is non-existent and pesky program managers don&rsquo;t set deadlines, this is perfectly fine. Unfortunately, that&rsquo;s not a world we have the benefit of living in.</p>
<p>What happens when we decide we need to migrate away from SendGrid for emails and use MailChimp instead? Similarly, what happens when we want to unit test our methods - are we going to use the real database in the tests? Worse, are we actually going to send real emails to potentially real email addresses and pay for it too? In the traditional JavaScript ecosystem, the methods of unit testing classes under this configuration are fraught with complexity and over-engineering. People bring in whole entire libraries simply to provide stubbing functionality, which adds all kinds of layers of indirection, and, even worse, can directly couple the tests to the implementation of the system under test, when, in reality, tests should never know how the real system works (this is known as black-box testing). We&rsquo;ll work to mitigate these issues as we discuss what the actual responsibility of <code>UserService</code> is and apply new techniques of dependency injection.</p>
<p>Consider, for a moment, what a <code>UserService</code> does. The whole point of the existence of <code>UserService</code> is to execute specific use cases involving users - registering them, reading them, updating them, etc. It&rsquo;s a best practice for classes and functions to have only one responsibility (SRP - the Single Responsibility Principle), and the responsibility of <code>UserService</code> is to handle user-related operations. Why, then, is <code>UserService</code> responsible for controlling the lifetime of <code>UserRepository</code> and <code>SendGridEmailProvider</code> in this example? Imagine if we had some other class used by <code>UserService</code> which opened a long-running connection. Should <code>UserService</code> be responsible for disposing of that connection too? Of course not. All of these dependencies have a lifetime associated with them - they could be singletons, they could be transient and scoped to a specific HTTP Request, etc. The controlling of these lifetimes is well outside the purview of <code>UserService</code>. So, to solve these issues, we&rsquo;ll inject all of the dependencies in, just like we saw before.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">UserRepository</span> }  <span style="color:#66d9ef">from</span>  <span style="color:#e6db74">&#39;./UserRepository.ts&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">SendGridEmailProvider</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./SendGridEmailProvider.ts&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserService</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">UserRepository</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">sendGridEmailProvider</span>: <span style="color:#66d9ef">SendGridEmailProvider</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">UserRepository</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">sendGridEmailProvider</span>: <span style="color:#66d9ef">SendGridEmailProvider</span>
</span></span><span style="display:flex;"><span>    ) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Yay! Dependencies are injected.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userRepository</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">sendGridEmailProvider</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">sendGridEmailProvider</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">dto</span>: <span style="color:#66d9ef">IRegisterUserDto</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// User object &amp; validation
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">dto</span>.<span style="color:#a6e22e">email</span>))
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">DuplicateEmailError</span>());
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Database persistence
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Send welcome email
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">sendGridEmailProvider</span>.<span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">email</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Great - now <code>UserService</code> receives pre-instantiated objects, and whichever piece of code calls and creates a new <code>UserService</code> is the piece of code in charge of controlling the lifetime of the dependencies. We&rsquo;ve inverted control away from <code>UserService</code> and up to a higher level. If I only wanted to show how we could inject dependencies through the constructor as to explain the basic tenant of dependency injection, I could stop here. There are still some problems from a design perspective, however, which when rectified, will serve to make our use of dependency injection all the more powerful.</p>
<p>Firstly, why does <code>UserService</code> know that we&rsquo;re using SendGrid for emails? Secondly, both dependencies are on concrete classes - the concrete <code>UserRepository</code> and the concrete <code>SendGridEmailProvider</code>. This relationship is too rigid - we&rsquo;re stuck having to pass in some object that <strong>is a</strong> <code>UserRepository</code> and <strong>is a</strong> <code>SendGridEmailProvider</code>.</p>
<p>This isn&rsquo;t great because we want <code>UserService</code> to be completely agnostic to the implementation of its dependencies. By having <code>UserService</code> be blind in that manner, we can swap out the implementations without affecting the service at all - this means, if we decide to migrate away from SendGrid and use MailChimp instead, we can do so. It also means if we want to fake out the email provider for tests, we can do that too. What would be useful is if we could define some public interface and force that incoming dependencies abide by that interface, while still having <code>UserService</code> be agnostic to implementation details. Put another way, we need to force <code>UserService</code> to only depend on an abstraction of its dependencies, and not it&rsquo;s actual concrete dependencies. We can do that through, well, interfaces.</p>
<p>Start by defining an interface for the <code>UserRepository</code> and implement it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// UserRepository.ts
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">dbDriver</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;pg-driver&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUserRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>: <span style="color:#66d9ef">User</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">email</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserRepository</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IUserRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>: <span style="color:#66d9ef">User</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... dbDriver.save(...)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... dbDriver.query(...)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">email</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... dbDriver.save(...)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>And define one for the email provider, also implementing it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// IEmailProvider.ts
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IEmailProvider</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">to</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// SendGridEmailProvider.ts
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">sendMail</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;sendgrid&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">IEmailProvider</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./IEmailProvider&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">SendGridEmailProvider</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IEmailProvider</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">to</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ... await sendMail(...);
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><em><strong>Note:</strong> This is the <a href="https://en.wikipedia.org/wiki/Adapter_pattern">Adapter Pattern</a> from the Gang of Four Design Patterns.</em></p>
<p>Now, our <code>UserService</code> can depend on the interfaces rather than the concrete implementations of the dependencies:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">IUserRepository</span> }  <span style="color:#66d9ef">from</span>  <span style="color:#e6db74">&#39;./UserRepository.ts&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">IEmailProvider</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;./SendGridEmailProvider.ts&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserService</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">IUserRepository</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">emailProvider</span>: <span style="color:#66d9ef">IEmailProvider</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">IUserRepository</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">emailProvider</span>: <span style="color:#66d9ef">IEmailProvider</span>
</span></span><span style="display:flex;"><span>    ) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Double yay! Injecting dependencies and coding against interfaces.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userRepository</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">emailProvider</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">emailProvider</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">dto</span>: <span style="color:#66d9ef">IRegisterUserDto</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// User object &amp; validation
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">dto</span>.<span style="color:#a6e22e">email</span>))
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">DuplicateEmailError</span>());
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Database persistence
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Send welcome email
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">emailProvider</span>.<span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">email</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>If interfaces are new to you, this might look very, very complex. Indeed, the concept of building loosely coupled software might be new to you too. Think about wall receptacles. You can plug any device into any receptacle so long as the plug fits the outlet. That&rsquo;s loose coupling in action. Your toaster is not hard-wired into the wall, because if it was, and you decide to upgrade your toaster, you&rsquo;re out of luck. Instead, outlets are used, and the outlet defines the interface. Similarly, when you plug an electronic device into your wall receptacle, you&rsquo;re not concerned with the voltage potential, the max current draw, the AC frequency, etc., you just care if the plug fits into the outlet. You could have an electrician come in and change all the wires behind that outlet, and you won&rsquo;t have any problems plugging in your toaster, so long as that outlet doesn&rsquo;t change. Further, your electricity source could be switched to come from the city or your own solar panels, and once again, you don&rsquo;t care as long as you can still plug into that outlet. The interface is the outlet, providing &ldquo;plug-and-play&rdquo; functionality. In this example, the wiring in the wall and the electricity source is akin to the dependencies and your toaster is akin to the <code>UserService</code> (it has a dependency on the electricity) - the electricity source can change and the toaster still works fine and need not be touched, because the outlet, acting as the interface, defines the standard means for both to communicate. In fact, you could say that the outlet acts as an &ldquo;abstraction&rdquo; of the wall wiring, the circuit breakers, the electrical source, etc.</p>
<p>It is a common and well-regarded principle of software design, for the reasons above, to code against interfaces (abstractions) and not implementations, which is what we&rsquo;ve done here. In doing so, we&rsquo;re given the freedom to swap out implementations as we please, for those implementations are hidden behind the interface (just like wall wiring is hidden behind the outlet), and so the business logic that uses the dependency never has to change so long as the interface never changes. Remember, <code>UserService</code> only needs to know what functionality is offered by its dependencies, not how that functionality is supported behind the scenes. That&rsquo;s why using interfaces works.</p>
<p>These two simple changes of utilizing interfaces and injecting dependencies make all the difference in the world when it comes to building loosely coupled software and solves all of the problems we ran into above.</p>
<p>If we decide tomorrow that we want to rely on MailChimp for emails, we simply create a new MailChimp class that honors the <code>IEmailProvider</code> interface and inject it in instead of SendGrid. The actual <code>UserService</code> class never has to change even though we&rsquo;ve just made a ginormous change to our system by switching to a new email provider. The beauty of these patterns is that <code>UserService</code> remains blissfully unaware of how the dependencies it uses work behind the scenes. The interface serves as the architectural boundary between both components, keeping them appropriately decoupled.</p>
<p>Additionally, when it comes to testing, we can create fakes that abide by the interfaces and inject them instead. Here, you can see a fake repository and a fake email provider.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// Both fakes:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FakeUserRepository</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IUserRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">users</span>: <span style="color:#66d9ef">User</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>: <span style="color:#66d9ef">User</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">users</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userOrNone</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">users</span>.<span style="color:#a6e22e">find</span>(<span style="color:#a6e22e">u</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">u</span>.<span style="color:#a6e22e">id</span> <span style="color:#f92672">===</span> <span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">userOrNone</span>
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">?</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">resolve</span>(<span style="color:#a6e22e">userOrNone</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">NotFoundError</span>());
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">existsByEmail</span>(<span style="color:#a6e22e">email</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> Boolean(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">users</span>.<span style="color:#a6e22e">find</span>(<span style="color:#a6e22e">u</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">u</span>.<span style="color:#a6e22e">email</span> <span style="color:#f92672">===</span> <span style="color:#a6e22e">email</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">getPersistedUserCount</span> <span style="color:#f92672">=</span> () <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">users</span>.<span style="color:#a6e22e">length</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FakeEmailProvider</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IEmailProvider</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">emailRecipients</span>: <span style="color:#66d9ef">string</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">to</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">emailRecipients</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">to</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">wasEmailSentToRecipient</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">recipient</span>: <span style="color:#66d9ef">string</span>) <span style="color:#f92672">=&gt;</span>
</span></span><span style="display:flex;"><span>        Boolean(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">emailRecipients</span>.<span style="color:#a6e22e">find</span>(<span style="color:#a6e22e">r</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">r</span> <span style="color:#f92672">===</span> <span style="color:#a6e22e">recipient</span>));
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Notice that both fakes implement the same interfaces that <code>UserService</code> expects its dependencies to honor. Now, we can pass these fakes into <code>UserService</code> instead of the real classes and <code>UserService</code> will be none the wiser, it&rsquo;ll use them just as if they were the real deal. The reason it can do that is because it knows that all of the methods and properties it wants to use on its dependencies do indeed exist and are indeed accessible (because they implement the interfaces), which is all <code>UserService</code> needs to know (i.e, not how the dependencies work).</p>
<p>We&rsquo;ll inject these two during tests, and it&rsquo;ll make the testing process so much easier and so much more straightforward than what you might be used to when dealing with over-the-top mocking and stubbing libraries, working with Jest&rsquo;s own internal tooling, or trying to monkey-patch.</p>
<p>Here are actual tests using the fakes.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// Fakes
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">fakeUserRepository</span>: <span style="color:#66d9ef">FakeUserRepository</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">fakeEmailProvider</span>: <span style="color:#66d9ef">FakeEmailProvider</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// SUT
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">userService</span>: <span style="color:#66d9ef">UserService</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// We want to clean out the internal arrays of both fakes 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// before each test.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">beforeEach</span>(() <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">fakeUserRepository</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">FakeUserRepository</span>();
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">fakeEmailProvider</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">FakeEmailProvider</span>();
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">userService</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">UserService</span>(<span style="color:#a6e22e">fakeUserRepository</span>, <span style="color:#a6e22e">fakeEmailProvider</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// A factory to easily create DTOs.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Here, we have the optional choice of overriding the defaults
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// thanks to the built in `Partial` utility type of TypeScript.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">createSeedRegisterUserDto</span>(<span style="color:#a6e22e">opts?</span>: <span style="color:#66d9ef">Partial</span>&lt;<span style="color:#f92672">IRegisterUserDto</span>&gt;)<span style="color:#f92672">:</span> <span style="color:#a6e22e">IRegisterUserDto</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">id</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;someId&#39;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">email</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;example@domain.com&#39;</span>,
</span></span><span style="display:flex;"><span>        ...<span style="color:#a6e22e">opts</span>
</span></span><span style="display:flex;"><span>    };
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">test</span>(<span style="color:#e6db74">&#39;should correctly persist a user and send an email&#39;</span>, <span style="color:#66d9ef">async</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Arrange
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dto</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">createSeedRegisterUserDto</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Act
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">userService</span>.<span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Assert
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">expectedUser</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">persistedUser</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">fakeUserRepository</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">dto</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">wasEmailSent</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">fakeEmailProvider</span>.<span style="color:#a6e22e">wasEmailSentToRecipient</span>(<span style="color:#a6e22e">dto</span>.<span style="color:#a6e22e">email</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">expect</span>(<span style="color:#a6e22e">persistedUser</span>).<span style="color:#a6e22e">toEqual</span>(<span style="color:#a6e22e">expectedUser</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">expect</span>(<span style="color:#a6e22e">wasEmailSent</span>).<span style="color:#a6e22e">toBe</span>(<span style="color:#66d9ef">true</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">test</span>(<span style="color:#e6db74">&#39;should reject with a DuplicateEmailError if an email already exists&#39;</span>, <span style="color:#66d9ef">async</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Arrange
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">existingEmail</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;john.doe@live.com&#39;</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dto</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">createSeedRegisterUserDto</span>({ <span style="color:#a6e22e">email</span>: <span style="color:#66d9ef">existingEmail</span> });
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">existingUser</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">fakeUserRepository</span>.<span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">existingUser</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Act, Assert
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">expect</span>(<span style="color:#a6e22e">userService</span>.<span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">dto</span>))
</span></span><span style="display:flex;"><span>        .<span style="color:#a6e22e">rejects</span>.<span style="color:#a6e22e">toBeInstanceOf</span>(<span style="color:#a6e22e">DuplicateEmailError</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">expect</span>(<span style="color:#a6e22e">fakeUserRepository</span>.<span style="color:#a6e22e">getPersistedUserCount</span>()).<span style="color:#a6e22e">toBe</span>(<span style="color:#ae81ff">1</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">test</span>(<span style="color:#e6db74">&#39;should correctly return a user&#39;</span>, <span style="color:#66d9ef">async</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Arrange
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">User</span>.<span style="color:#a6e22e">fromDto</span>(<span style="color:#a6e22e">createSeedRegisterUserDto</span>());
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">fakeUserRepository</span>.<span style="color:#a6e22e">addUser</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Act
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">receivedUser</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">userService</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Assert
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">expect</span>(<span style="color:#a6e22e">receivedUser</span>).<span style="color:#a6e22e">toEqual</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>You&rsquo;ll notice a few things here - the hand-written fakes are very simple. There&rsquo;s no complexity from mocking frameworks which only serve to obfuscate. Everything is hand-rolled and that means there is no magic in the codebase. Asynchronous behavior is faked to match the interfaces. I use async/await in the tests even though all behavior is synchronous because I feel that it more closely matches how I&rsquo;d expect the operations to work in the real world and because by adding async/await, I can run this same test suite against real implementations too in addition to the fakes, thus handing asynchrony appropriately is required. In fact, in real life, I would most likely not even worry about mocking the database and would instead use a local DB in a Docker container until there were so many tests that I had to mock it away for performance. I could then run the in-memory DB tests after every single change and reserve the real local DB tests for right before committing changes and for on the build server in the CI/CD pipeline.</p>
<p>In the first test, in the &ldquo;arrange&rdquo; section, we simply create the DTO. In the &ldquo;act&rdquo; section, we call the system under test and execute its behavior. Things get slightly more complex when making assertions. Remember, at this point in the test, we don&rsquo;t even know if the user was saved correctly. So, we define what we expect a persisted user to look like, and then we call the fake Repository and ask it for a user with the ID we expect. If the <code>UserService</code> didn&rsquo;t persist the user correctly, this will throw a <code>NotFoundError</code> and the test will fail, otherwise, it will give us back the user. Next, we call the fake email provider and ask it if it recorded sending an email to that user. Finally, we make the assertions with Jest and that concludes the test. It&rsquo;s expressive and reads just like how the system is actually working. There&rsquo;s no indirection from mocking libraries and there&rsquo;s no coupling to the implementation of the <code>UserService</code>.</p>
<p>In the second test, we create an existing user and add it to the repository, then we try to call the service again using a DTO that has already been used to create and persist a user, and we expect that to fail. We also assert that no new data was added to the repository.</p>
<p>For the third test, the &ldquo;arrange&rdquo; section now consists of creating a user and persisting it to the fake Repository. Then, we call the SUT, and finally, check if the user that comes back is the one we saved in the repo earlier.</p>
<p>These examples are relatively simple, but when things get more complex, being able to rely on dependency injection and interfaces in this manner keeps your code clean and makes writing tests a joy.</p>
<p><em><strong>A brief aside on testing:</strong> In general, you don&rsquo;t need to mock out every dependency that the code uses. Many people, erroneously, claim that a &ldquo;unit&rdquo; in a &ldquo;unit test&rdquo; is one function or one class. That could not be more incorrect. The &ldquo;unit&rdquo; is defined as the &ldquo;unit of functionality&rdquo; or the &ldquo;unit of behavior&rdquo;, not one function or class. So if a unit of behavior uses 5 different classes, you don&rsquo;t need to mock out all those classes <em>unless</em> they reach outside of the boundary of the module. In this case, I mocked the database and I mocked the email provider because I have no choice. If I don&rsquo;t want to use a real database and I don&rsquo;t want to send an email, I have to mock them out. But if I had a bunch more classes that didn&rsquo;t do anything across the network, I would not mock them because they&rsquo;re implementation details of the unit of behavior. I could also decide against mocking the database and emails and spin up a real local database and a real SMTP server, both in Docker containers. On the first point, I have no problem using a real database and still calling it a unit test so long as it&rsquo;s not too slow. Generally, I&rsquo;d use the real DB first until it became too slow and I had to mock, as discussed above. But, no matter what you do, you have to be pragmatic - sending welcome emails is not a mission-critical operation, thus we don&rsquo;t need to go that far in terms of SMTP servers in Docker containers. Whenever I do mock, I would be very unlikely to use a mocking framework or try to assert on the number of times called or parameters passed except in very rare cases, because that would couple tests to the implementation of the system under test, and they should be agnostic to those details.</em></p>
<h3 id="performing-dependency-injection-without-classes-and-constructors">Performing Dependency Injection without Classes and Constructors</h3>
<p>So far, throughout the article, we&rsquo;ve worked exclusively with classes and injected the dependencies through the constructor. If you&rsquo;re taking a functional approach to development and wish not to use classes, one can still obtain the benefits of dependency injection using function arguments. For example, our <code>UserService</code> class above could be refactored into:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">makeUserService</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">IUserRepository</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">emailProvider</span>: <span style="color:#66d9ef">IEmailProvider</span>
</span></span><span style="display:flex;"><span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">IUserService</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">registerUser</span>: <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">dto</span> <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        },
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">findUserById</span>: <span style="color:#66d9ef">id</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">findUserById</span>(<span style="color:#a6e22e">id</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>It&rsquo;s a factory that receives the dependencies and constructs the service object. We can also inject dependencies into Higher Order Functions. A typical example would be creating an Express Middleware function that gets a <code>UserRepository</code> and an <code>ILogger</code> injected:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">authProvider</span>(<span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">IUserRepository</span>, <span style="color:#a6e22e">logger</span>: <span style="color:#66d9ef">ILogger</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>: <span style="color:#66d9ef">Request</span>, <span style="color:#a6e22e">res</span>: <span style="color:#66d9ef">Response</span>, <span style="color:#a6e22e">next</span>: <span style="color:#66d9ef">NextFunction</span>) <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// Has access to userRepository, logger, req, res, and next.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In the first example, I didn&rsquo;t define the type of <code>dto</code> and <code>id</code> because if we define an interface called <code>IUserService</code> containing the method signatures for the service, then the TS Compiler will infer the types automatically. Similarly, had I defined a function signature for the Express Middleware to be the return type of <code>authProvider</code>, I wouldn&rsquo;t have had to declare the argument types there either.</p>
<p>If we considered the email provider and the repository to be functional too, and if we injected their specific dependencies as well instead of hard coding them, the root of the application could look like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">sendMail</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;sendgrid&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">async</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">main() {</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>();
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dbConnection</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">connectToDatabase</span>();
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Change emailProvider to `makeMailChimpEmailProvider` whenever we want
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// with no changes made to dependent code.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userRepository</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">makeUserRepository</span>(<span style="color:#a6e22e">dbConnection</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">emailProvider</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">makeSendGridEmailProvider</span>(<span style="color:#a6e22e">sendMail</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userService</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">makeUserService</span>(<span style="color:#a6e22e">userRepository</span>, <span style="color:#a6e22e">emailProvider</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Put this into another file. It&#39;s a controller action.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/login&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">userService</span>.<span style="color:#a6e22e">registerUser</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span> <span style="color:#66d9ef">as</span> <span style="color:#a6e22e">IRegisterUserDto</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>();
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Put this into another file. It&#39;s a controller action.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">app</span>.<span style="color:#66d9ef">delete</span>(
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#39;/me&#39;</span>, 
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">authProvider</span>(<span style="color:#a6e22e">userRepository</span>, <span style="color:#a6e22e">emailProvider</span>), 
</span></span><span style="display:flex;"><span>        (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) <span style="color:#f92672">=&gt;</span> { ... }
</span></span><span style="display:flex;"><span>    );
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Notice that we fetch the dependencies that we need, like a database connection or third-party library functions, and then we utilize factories to make our first-party dependencies using the third-party ones. We then pass them into the dependent code. Since everything is coded against abstractions, I can swap out either <code>userRepository</code> or <code>emailProvider</code> to be any different function or class with any implementation I want (that still implements the interface correctly) and <code>UserService</code> will just use it with no changes needed, which, once again, is because <code>UserService</code> cares about nothing but the public interface of the dependencies, not how the dependencies work.</p>
<p>As a disclaimer, I want to point out a few things. As stated earlier, this demo was optimized for showing how dependency injection makes life easier, and thus it wasn&rsquo;t optimized in terms of system design best practices insofar as the patterns surrounding how Repositories and DTOs should technically be used. In real life, one has to deal with managing transactions across repositories and the DTO should generally not be passed into service methods, but rather mapped in the controller to allow the presentation layer to evolve separately from the application layer. The <code>userSerivce.findById</code> method here also neglects to map the User domain object to a DTO, which it should do in real life. None of this affects the DI implementation though, I simply wanted to keep the focus on the benefits of DI itself, not Repository design, Unit of Work management, or DTOs. Finally, although this may look a little like the NestJS framework in terms of the manner of doing things, it&rsquo;s not, and I actively discourage people from using NestJS for reasons outside the scope of this article.</p>
<h3 id="a-brief-theoretical-overview">A Brief Theoretical Overview</h3>
<p>All applications are made up of collaborating components, and the manner in which those collaborators collaborate and are managed will decide how much the application will resist refactoring, resist change, and resist testing. Dependency injection mixed with coding against interfaces is a primary method (among others) of reducing the coupling of collaborators within systems, and making them easily swappable. This is the hallmark of a highly cohesive and loosely coupled design.</p>
<p>The individual components that make up applications in non-trivial systems must be decoupled if we want the system to be maintainable, and the way we achieve that level of decoupling, as stated above, is by depending upon abstractions, in this case, interfaces, rather than concrete implementations, and utilizing dependency injection. Doing so provides loose coupling and gives us the freedom of swapping out implementations without needing to make any changes on the side of the dependent component/collaborator and solves the problem that dependent code has no business managing the lifetime of its dependencies and shouldn&rsquo;t know how to create them or dispose of them.</p>
<p>Despite the simplicity of what we&rsquo;ve seen thus far, there&rsquo;s a lot more complexity that surrounds dependency injection.</p>
<p>Injection of dependencies can come in many forms. Constructor Injection is what we have been using here since dependencies are injected into a constructor. There also exists Setter Injection and Interface Injection. In the case of the former, the dependent component will expose a setter method which will be used to inject the dependency - that is, it could expose a method like <code>setUserRepository(userRepository: UserRepository)</code>. In the last case, we can define interfaces through which to perform the injection, but I&rsquo;ll omit the explanation of the last technique here for brevity since we&rsquo;ll spend more time discussing it and more in the second article of this series.</p>
<p>Because wiring up dependencies manually can be difficult, various IoC Frameworks and Containers exist. These containers store your dependencies and resolve the correct ones at runtime, often through Reflection in languages like C# or Java, exposing various configuration options for dependency lifetime. Despite the benefits that IoC Containers provide, there are cases to be made for moving away from them, and only resolving dependencies manually. To hear more about this, see Greg Young&rsquo;s <a href="https://www.infoq.com/presentations/8-lines-code-refactoring/">8 Lines of Code talk</a>.</p>
<p>Additionally, DI Frameworks and IoC Containers can provide too many options, and many rely on decorators or attributes to perform techniques such as setter or field injection. I look down on this kind of approach because, if you think about it intuitively, the point of dependency injection is to achieve loose coupling, but if you begin to sprinkle IoC Container-specific decorators all over your business logic, while you may have achieved decoupling from the dependency, you&rsquo;ve inadvertently coupled yourself to the IoC Container. IoC Containers like Awilix solve this problem since they remain divorced from your application&rsquo;s business logic.</p>
<h3 id="conclusion">Conclusion</h3>
<p>This article served to depict only a very practical example of dependency injection in use and mostly neglected the theoretical attributes. I did it this way in order to make it easier to understand what dependency injection is at its core in a manner divorced from the rest of the complexity that people usually associate with the concept. In the second article of this series, we&rsquo;ll take a much, much more in-depth look, including at:</p>
<ul>
<li>The difference between Dependency Injection and Dependency Inversion and Inversion of Control</li>
<li>Dependency Injection anti-patterns</li>
<li>IoC Container anti-patterns</li>
<li>The role of IoC Containers</li>
<li>The different types of dependency lifetimes</li>
<li>How IoC Containers are designed</li>
<li>Dependency Injection with React</li>
<li>Advanced testing scenarios</li>
<li>And more</li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>Understanding TypeScript Generics</title>
            <link>/2020/10/understanding-typescript-generics/</link>
            <pubDate>Wed, 14 Oct 2020 11:10:54 -0500</pubDate>
            
            <guid>/2020/10/understanding-typescript-generics/</guid>
            <description>This article was first written for Smashing Magazine on October 10th, 2020. You can find it here.
Introduction In this article, we’ll be learning the concept of Generics in TypeScript and examining how Generics can be used to write modular, decoupled, and reusable code. Along the way, we’ll briefly discuss how they fit into better testing patterns, approaches to error handling, and domain/data-access separation.
A Real-World Example I want to enter into the world of Generics not by explaining what they are, but rather by providing an intuitive example for why they are useful.</description>
            <content type="html"><![CDATA[<blockquote>
<p>This article was first written for Smashing Magazine on October 10th, 2020. You can find it <a href="https://www.smashingmagazine.com/2020/10/understanding-typescript-generics/">here</a>.</p>
</blockquote>
<h2 id="introduction">Introduction</h2>
<p>In this article, we’ll be learning the concept of Generics in TypeScript and examining how Generics can be used to write modular, decoupled, and reusable code. Along the way, we’ll briefly discuss how they fit into better testing patterns, approaches to error handling, and domain/data-access separation.</p>
<h2 id="a-real-world-example">A Real-World Example</h2>
<p>I want to enter into the world of Generics <strong>not</strong> by explaining what they are, but rather by providing an intuitive example for why they are useful. Suppose you&rsquo;ve been tasked with building a feature-rich dynamic list. You could call it an array, an <code>ArrayList</code>, a <code>List</code>, a <code>std::vector</code>, or whatever, depending upon your language background. Perhaps this data structure must have in-built or swappable buffer systems as well (like a circular buffer insertion option). It will be a wrapper around the normal JavaScript array so that we can work with our structure instead of plain arrays.</p>
<p>The immediate issue you&rsquo;ll come across is that of constraints imposed by the type system. You can&rsquo;t, at this point, accept any type you want into a function or method in a nice clean way (we&rsquo;ll revisit this statement later).</p>
<p>The only obvious solution is to replicate our data structure for all different types:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">intList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">IntegerList</span>.<span style="color:#a6e22e">create</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">intList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#ae81ff">4</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">stringList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">StringList</span>.<span style="color:#a6e22e">create</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">stringList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#39;hello&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">UserList</span>.<span style="color:#a6e22e">create</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>));
</span></span></code></pre></div><p><em>The <code>.create()</code> syntax here might look arbitrary, and indeed, <code>new SomethingList()</code> would be more straight-forward, but you&rsquo;ll see why we use this static factory method later. Internally, the <code>create</code> method calls the constructor.</em></p>
<p>This is terrible. We have a lot of logic within this collection structure, and we&rsquo;re blatantly duplicating it to support different use cases, completely breaking the DRY Principle in the process. When we decide to change our implementation, we&rsquo;ll have to manually propagate/reflect those changes across all structures and types we support, including user-defined types, as in the latter example above. Suppose the collection structure itself was 100 lines long - it would be a nightmare to maintain multiple different implementations where the only difference between them is types.</p>
<p>An immediate solution that might come to mind, especially if you have an OOP mindset, is to consider a root &ldquo;supertype&rdquo;, if you will. In C#, for example, there consists a type by the name of <code>object</code>, and <code>object</code> is an alias for the <code>System.Object</code> class. In C#&rsquo;s type system, all types, be they predefined or user-defined and be they reference types or value types, inherit either directly or indirectly from <code>System.Object</code>. This means that any value can be assigned to a variable of type <code>object</code> (without getting into stack/heap and boxing/unboxing semantics).</p>
<p>In this case, our issue appears solved. We can just use a type like <code>any</code> and that will allow us to store anything we want within our collection without having to duplicate the structure, and indeed, that&rsquo;s very true:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">intList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">AnyList</span>.<span style="color:#a6e22e">create</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">intList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#ae81ff">4</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">stringList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">AnyList</span>.<span style="color:#a6e22e">create</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">stringList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#39;hello&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">AnyList</span>.<span style="color:#a6e22e">create</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>));
</span></span></code></pre></div><p>Let&rsquo;s look at the actual implementation of our list using <code>any</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AnyList</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">any</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">any</span>[]) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Some more construction work.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">any</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">value</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">where</span>(<span style="color:#a6e22e">predicate</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">any</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">boolean</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">AnyList</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">AnyList</span>.<span style="color:#66d9ef">from</span>(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">filter</span>(<span style="color:#a6e22e">predicate</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">select</span>(<span style="color:#a6e22e">selector</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">any</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">any</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">AnyList</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">AnyList</span>.<span style="color:#66d9ef">from</span>(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">selector</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">toArray</span>()<span style="color:#f92672">:</span> <span style="color:#66d9ef">any</span>[] {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">from</span>(<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">any</span>[])<span style="color:#f92672">:</span> <span style="color:#a6e22e">AnyList</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Perhaps we perform some logic here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">AnyList</span>(<span style="color:#a6e22e">values</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#a6e22e">create</span>(<span style="color:#a6e22e">values?</span>: <span style="color:#66d9ef">any</span>[])<span style="color:#f92672">:</span> <span style="color:#a6e22e">AnyList</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">AnyList</span>(<span style="color:#a6e22e">values</span> <span style="color:#f92672">??</span> []);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Other collection functions.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>All the methods are relatively simple, but we&rsquo;ll start with the constructor. Its visibility is private, for we&rsquo;ll assume that our list is complex and we wish to disallow arbitrary construction. We also may want to perform logic prior to construction, so for these reasons, and to keep the constructor pure, we delegate these concerns to static factory/helper methods, which is considered a good practice.</p>
<p>The static methods <code>from</code> and <code>create</code> are provided. The method <code>from</code> accepts an array of values, performs custom logic, and then uses them to construct the list. The <code>create</code> static method takes an optional array of values for in the event that we want to seed our list with initial data. The &ldquo;nullish coalescing operator&rdquo; (<code>??</code>) is used to construct the list with an empty array in the event that one is not provided. If the left side of the operand is <code>null</code> or <code>undefined</code>, we&rsquo;ll fall back to the right side, for in this case, <code>values</code> is optional, and thus may be <code>undefined</code>. You can learn more about nullish coalescing at the relevant <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing">TypeScript documentation page</a>.</p>
<p>I&rsquo;ve also added a <code>select</code> and a <code>where</code> method. These methods just wrap JavaScript&rsquo;s <code>map</code> and <code>filter</code> respectively. <code>select</code> permits us to project an array of elements into a new form based on the provided selector function, and <code>where</code> permits us to filter out certain elements based on the provided predicate function. The <code>toArray</code> method simply converts the list to an array by returning the array reference we hold internally.</p>
<p>Finally, suppose that the <code>User</code> class contains a <code>getName</code> method which returns a name and also accepts a name as its first and only constructor argument.</p>
<blockquote>
<p><em>Note: Some readers will recognize <code>Where</code> and <code>Select</code> from C#&rsquo;s LINQ, but keep in mind, I&rsquo;m trying to keep this simple, thus I&rsquo;m not worried about laziness or deferred execution. Those are optimizations that could and should be made in real life.</em></p>
<p><em>Further, as an interesting note, I want to discuss the meaning of &ldquo;predicate&rdquo;. In Discrete Mathematics and Propositional Logic, we have the concept of a &ldquo;proposition&rdquo;. A proposition is some statement that can be considered true or false, such as &ldquo;four is divisible by two&rdquo;. A &ldquo;predicate&rdquo; is a proposition that contains one or more variables, thus the truthfulness of the proposition depends upon that of those variables. You can think about it like a function, such as <code>P(x) = x is divisible by two</code>, for we need to know the value of <code>x</code> to determine if the statement is true or false.</em> You can learn more about predicate logic <a href="http://www1.spms.ntu.edu.sg/~frederique/dm3.pdf">here</a>.</p>
</blockquote>
<p>There are a few issues that are going to arise from the use of <code>any</code>. The TypeScript compiler knows nothing about the elements inside the list/internal array, thus it won&rsquo;t provide any help inside of <code>where</code> or <code>select</code> or when adding elements:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// Providing seed data.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">AnyList</span>.<span style="color:#a6e22e">create</span>([<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>)]);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is fine and expected.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Tom&#39;</span>));
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Alice&#39;</span>));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is an acceptable input to the TS Compiler,
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// but it&#39;s not what we want. We&#39;ll definitely
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// be surprised later to find strings in a list
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// of users.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#39;Hello, World!&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Also acceptable. We have a large tuple
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// at this point rather than a homogeneous array.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#ae81ff">0</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This compiles just fine despite the spelling mistake (extra &#39;s&#39;):
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// The type of `users` is any.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">users</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">where</span>(<span style="color:#a6e22e">user</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">getNames</span>() <span style="color:#f92672">===</span> <span style="color:#e6db74">&#39;Jamie&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Property `ssn` doesn&#39;t even exist on a `user`, yet it compiles.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">users</span>.<span style="color:#a6e22e">toArray</span>()[<span style="color:#ae81ff">0</span>].<span style="color:#a6e22e">ssn</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;000000000&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// `usersWithId` is, again, just `any`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">usersWithId</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">select</span>(<span style="color:#a6e22e">user</span> <span style="color:#f92672">=&gt;</span> ({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">newUuid</span>(),
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span>: <span style="color:#66d9ef">user.getName</span>()
</span></span><span style="display:flex;"><span>}));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Oops, it&#39;s &#34;id&#34; not &#34;ID&#34;, but TS doesn&#39;t help us. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// We compile just fine.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">usersWithId</span>.<span style="color:#a6e22e">toArray</span>()[<span style="color:#ae81ff">0</span>].<span style="color:#a6e22e">ID</span>);
</span></span></code></pre></div><p>Since TypeScript only knows that the type of all array elements is <code>any</code>, it can&rsquo;t help us at compile time with the non-existent properties or the <code>getNames</code> function that doesn&rsquo;t even exist, thus this code will result in multiple unexpected runtime errors.</p>
<p>To be honest, things are beginning to look quite dismal. We tried implementing our data structure for each concrete type we wished to support, but we quickly realized that that was not in any way maintainable. Then, we thought we were getting somewhere by using <code>any</code>, which is analogous to depending upon a root supertype in an inheritance chain from which all types derive, but we concluded that we lose type-safety with that method. What&rsquo;s the solution, then?</p>
<p>It turns out that, at the beginning of the article, I lied (kind of):</p>
<blockquote>
<p>&ldquo;You can&rsquo;t, at this point, accept any type you want into a function or method in a nice clean way.&rdquo;</p>
</blockquote>
<p>You actually can, and that&rsquo;s where Generics come in. Notice I said &ldquo;at this point&rdquo;, for I was assuming we didn&rsquo;t know about Generics at that point in the article.</p>
<p>I&rsquo;ll start by showing the full implementation of our List structure with Generics, and then we&rsquo;ll take a step back, discuss what they actually are, and determine their syntax more formally. I&rsquo;ve named it <code>TypedList</code> to differentiate from our earlier <code>AnyList</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">T</span>[]) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">value</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">where</span>(<span style="color:#a6e22e">predicate</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">boolean</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">filter</span>(<span style="color:#a6e22e">predicate</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">select</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">selector</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">selector</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">toArray</span>()<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span>[] {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">U</span>[])<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Perhaps we perform some logic here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values?</span>: <span style="color:#66d9ef">U</span>[])<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span> <span style="color:#f92672">??</span> []);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Other collection functions.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// ..
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Let&rsquo;s try making the same mistakes as earlier once again:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// Here&#39;s the magic. `TypedList` will operate on objects
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// of type `User` due to the `&lt;User&gt;` syntax.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">User</span>&gt;([<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>)]);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// The compiler expects this.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Tom&#39;</span>));
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>(<span style="color:#e6db74">&#39;Alice&#39;</span>));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Argument of type &#39;0&#39; is not assignable to parameter 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// of type &#39;User&#39;. ts(2345)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#ae81ff">0</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Property &#39;getNames&#39; does not exist on type &#39;User&#39;. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Did you mean &#39;getName&#39;? ts(2551)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Note: TypeScript infers the type of `users` to be
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// `TypedList&lt;User&gt;`
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">users</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">where</span>(<span style="color:#a6e22e">user</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">user</span>.<span style="color:#a6e22e">getNames</span>() <span style="color:#f92672">===</span> <span style="color:#e6db74">&#39;Jamie&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Property &#39;ssn&#39; does not exist on type &#39;User&#39;. ts(2339)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">users</span>.<span style="color:#a6e22e">toArray</span>()[<span style="color:#ae81ff">0</span>].<span style="color:#a6e22e">ssn</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;000000000&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// TypeScript infers `usersWithId` to be of type
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// `TypedList&lt;{ id: string, name: string }&gt;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">usersWithId</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userList</span>.<span style="color:#a6e22e">select</span>(<span style="color:#a6e22e">user</span> <span style="color:#f92672">=&gt;</span> ({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">newUuid</span>(),
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span>: <span style="color:#66d9ef">user.getName</span>()
</span></span><span style="display:flex;"><span>}));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Property &#39;ID&#39; does not exist on type &#39;{ id: string; name: string; }&#39;. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Did you mean &#39;id&#39;? ts(2551)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">usersWithId</span>.<span style="color:#a6e22e">toArray</span>()[<span style="color:#ae81ff">0</span>].<span style="color:#a6e22e">ID</span>)
</span></span></code></pre></div><p>As you can see, the TypeScript compiler is actively aiding us with type-safety. All of those comments are errors I receive from the compiler when attempting to compile this code. Generics have permitted us to specify a type that we wish to permit our list to operate on, and from that, TypeScript can tell the types of everything, all the way down to the properties of individual objects within the array.</p>
<p>The types we provide can be as simple or complex as we want them to be. Here, you can see we can pass both primitives and complex interfaces. We could also pass other arrays, or classes, or anything:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">numberList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">number</span>&gt;();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">numberList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#ae81ff">4</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">stringList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">string</span>&gt;();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">stringList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#39;Hello, World!&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Example of a complex type
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IAircraft</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">apuStatus</span>: <span style="color:#66d9ef">ApuStatus</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">inboardOneRPM</span>: <span style="color:#66d9ef">number</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">altimeter</span>: <span style="color:#66d9ef">number</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">tcasAlert</span>: <span style="color:#66d9ef">boolean</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">pushBackAndStart</span>()<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">ilsCaptureGlidescope</span>()<span style="color:#f92672">:</span> <span style="color:#66d9ef">boolean</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">getFuelStats</span>()<span style="color:#f92672">:</span> <span style="color:#a6e22e">IFuelStats</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">getTCASHistory</span>()<span style="color:#f92672">:</span> <span style="color:#a6e22e">ITCASHistory</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">aircraftList</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">IAircraft</span>&gt;();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">aircraftList</span>.<span style="color:#a6e22e">add</span>(<span style="color:#75715e">/* ... */</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Aggregate and generate report:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">stats</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">aircraftList</span>.<span style="color:#a6e22e">select</span>(<span style="color:#a6e22e">a</span> <span style="color:#f92672">=&gt;</span> ({
</span></span><span style="display:flex;"><span>    ...<span style="color:#a6e22e">a</span>.<span style="color:#a6e22e">getFuelStats</span>(),
</span></span><span style="display:flex;"><span>    ...<span style="color:#a6e22e">a</span>.<span style="color:#a6e22e">getTCASHistory</span>()
</span></span><span style="display:flex;"><span>}));
</span></span></code></pre></div><p>The peculiar uses of <code>T</code> and <code>U</code> and <code>&lt;T&gt;</code> and <code>&lt;U&gt;</code> in the <code>TypedList&lt;T&gt;</code> implementation are examples of Generics in action. Having fulfilled our directive of constructing a type-safe collection structure, we&rsquo;ll leave this example behind for now, and we&rsquo;ll return to it once we understand what Generics actually are, how they work, and their syntax. When I&rsquo;m learning a new concept, I always like to begin by seeing a complex example of the concept in use, so that when I start learning the basics, I can make connections between the basic topics and the existing example I have in my head.</p>
<h2 id="what-are-generics">What are Generics?</h2>
<p>A simple manner by which to understand Generics is to consider them as relatively analogous to placeholders or variables but for types. That&rsquo;s not to say that you can perform the same operations upon a generic type placeholder as you can a variable, but a generic type variable could be thought of as some placeholder that represents a concrete type that will be used in the future. That is, using Generics is a method of writing programs in terms of types that are to be specified at a later point in time. The reason why this is useful is because it allows us to build data structures that are reusable across the different types they operate upon (or type-agnostic).</p>
<p>That&rsquo;s not particularly the best of explanations, so to put it in more simple terms, as we&rsquo;ve seen, it is common in programming that we might need to build a function/class/data structure that will operate upon a certain type, but it is equally common that such a data structure needs to work across a variety of different types as well. If we were stuck in a position where we had to statically declare the concrete type upon which a data structure would operate at the time when we design the data structure (at compile time), we&rsquo;d very quickly find that we need to rebuild those structures in an almost-exactly-the-same-manner for every type we wish to support, as we saw in the examples above.</p>
<p>Generics help us to solve this problem by permitting us to defer the requirement for a concrete type until it is actually known.</p>
<h2 id="generics-in-typescript">Generics in TypeScript</h2>
<p>We now have somewhat of an organic idea for why Generics are useful and we&rsquo;ve seen a slightly complicated example of them in practice. For most, the <code>TypedList&lt;T&gt;</code> implementation probably already makes a lot of sense, especially if you come from a statically-typed language background, but I can remember having a difficult time understanding the concept when I was first learning, thus I want to build up to that example by starting with simple functions. Concepts related to abstraction in software can be notoriously difficult to internalize, so if the notion of Generics has not quite clicked yet, that&rsquo;s completely fine, and hopefully, by this article&rsquo;s closing, the idea will be at least somewhat intuitive.</p>
<p>To build up to being able to understand that example, let&rsquo;s work up from simple functions. We&rsquo;ll start with the &ldquo;Identity Function&rdquo;, which is what most articles, including the TypeScript documentation itself, like to use.</p>
<p>An &ldquo;Identity Function&rdquo;, in mathematics, is a function that maps its input directly to its output, such as <code>f(x) = x</code>. What you put in is what you get out. We can represent that, in JavaScript, as:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">identity</span>(<span style="color:#a6e22e">input</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">input</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Or, more tersely:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">identity</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">input</span> =&gt; <span style="color:#a6e22e">input</span>;
</span></span></code></pre></div><p>Trying to port this to TypeScript brings back the same type system issues we saw before. The solutions are typing with <code>any</code>, which we know is seldom a good idea, duplicating/overloading the function for each type (breaks DRY), or using Generics.</p>
<p>With the latter option, we can represent the function as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// ES5 Function
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">identity</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#a6e22e">input</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">input</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Arrow Function
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">identity</span> <span style="color:#f92672">=</span> &lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#a6e22e">input</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">input</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">identity</span>&lt;<span style="color:#f92672">number</span>&gt;(<span style="color:#ae81ff">5</span>));       <span style="color:#75715e">// 5
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">identity</span>&lt;<span style="color:#f92672">string</span>&gt;(<span style="color:#e6db74">&#39;hello&#39;</span>)); <span style="color:#75715e">// hello
</span></span></span></code></pre></div><p>The <code>&lt;T&gt;</code> syntax here declares this function as Generic. Just like a function allows us to pass an arbitrary input parameter into its argument list, with a Generic function, we can pass an arbitrary type parameter as well.</p>
<p>The <code>&lt;T&gt;</code> part of the signature of <code>identity&lt;T&gt;(input: T): T</code> and <code>&lt;T&gt;(input: T): T</code> in both cases declares that the function in question will accept one generic type parameter named <code>T</code>. Just like how variables can be of any name, so can our Generic placeholders, but it&rsquo;s a convention to use a capital letter &ldquo;T&rdquo; (&ldquo;T&rdquo; for &ldquo;Type&rdquo;) and to move down the alphabet as needed. Remember, <code>T</code> is a type, so we also state that we will accept one function argument of name <code>input</code> with a type of <code>T</code> and that our function will return a type of <code>T</code>. That&rsquo;s all the signature is saying. Try letting <code>T = string</code> in your head - replace all the <code>T</code>s with <code>string</code> in those signatures. See how nothing all that magical is going on? See how similar it is to the non-generic way you use functions every day?</p>
<p>Keep in mind what you already know about TypeScript and function signatures. All we&rsquo;re saying is that <code>T</code> is an arbitrary type that the user will provide when calling the function, just like <code>input</code> is an arbitrary value that the user will provide when calling the function. In this case, <code>input</code> must be whatever that type <code>T</code> is when the function is called in the <strong>future</strong>.</p>
<p>Next, in the &ldquo;future&rdquo;, in the two log statements, we &ldquo;pass in&rdquo; the concrete type we wish to use, just like we do a variable. Notice the switch in verbiage here - in the initial form of <code>&lt;T&gt; signature</code>, when declaring our function, it is generic - that is, it works on generic types, or types to be specified later. That&rsquo;s because we don&rsquo;t know what type the caller will wish to use when we actually write the function. But, when the caller calls the function, he/she knows exactly what type(s) they want to work with, which are <code>string</code> and <code>number</code> in this case.</p>
<p>You can imagine the idea of having a log function declared this way in a third-party library - the library author has no idea what types the developers who use the lib will want to use, so they make the function generic, essentially <em>deferring the need for concrete types until they are actually known.</em></p>
<p>I want to stress that you <strong>should</strong> think of this process in a similar fashion that you do the notion of passing a variable to a function for the purposes of gaining a more intuitive understanding. All we&rsquo;re doing now is passing a type too.</p>
<p>At the point where we called the function with the <code>number</code> parameter, the original signature, for all intents and purposes, could be thought of as <code>identity(input: number): number</code>. And, at the point where we called the function with the <code>string</code> parameter, again, the original signature might just as well have been <code>identity(input: string): string</code>. You can imagine that, when making the call, every generic <code>T</code> gets replaced with the concrete type you provide at that moment.</p>
<h3 id="exploring-generic-syntax">Exploring Generic Syntax</h3>
<p>There are different syntaxes and semantics for specifying generics in the context of ES5 Functions, Arrow Functions, Type Aliases, Interfaces, and Classes. We&rsquo;ll explore those differences in this section.</p>
<h3 id="exploring-generic-syntax---functions">Exploring Generic Syntax - Functions</h3>
<p>You&rsquo;ve seen a few examples of generic functions by now, but it&rsquo;s important to note that a generic function can accept more than one generic type parameter, just like it can variables. You could choose to ask for one, or two, or three, or however many types you want, all separated by commas (again, just like input arguments).</p>
<p>This function accepts three input types and randomly returns one of them:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">randomValue</span>&lt;<span style="color:#f92672">T</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">U</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">V</span>&gt;(
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">one</span>: <span style="color:#66d9ef">T</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">two</span>: <span style="color:#66d9ef">U</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">three</span>: <span style="color:#66d9ef">V</span>
</span></span><span style="display:flex;"><span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">U</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">V</span>  {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// This is a tuple if you&#39;re not familiar.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">options</span><span style="color:#f92672">:</span> [<span style="color:#a6e22e">T</span>, <span style="color:#a6e22e">U</span>, <span style="color:#a6e22e">V</span>] <span style="color:#f92672">=</span> [
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">one</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">two</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">three</span>
</span></span><span style="display:flex;"><span>    ];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">rndNum</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">getRndNumInInclusiveRange</span>(<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">2</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">options</span>[<span style="color:#a6e22e">rndNum</span>];
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Calling the function.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// `value` has type `string | number | IAircraft`
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">value</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">randomValue</span><span style="color:#f92672">&lt;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">string</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">number</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">IAircraft</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">&gt;</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">myString</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">myNumber</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">myAircraft</span>
</span></span><span style="display:flex;"><span>);
</span></span></code></pre></div><p>You can also see that the syntax is slightly different depending on whether we use an ES5 Function or an Arrow Function, but both declare the type parameters in the signature:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">randomValue</span> <span style="color:#f92672">=</span> &lt;<span style="color:#f92672">T</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">U</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">V</span>&gt;(
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">one</span>: <span style="color:#66d9ef">T</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">two</span>: <span style="color:#66d9ef">U</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">three</span>: <span style="color:#66d9ef">V</span>
</span></span><span style="display:flex;"><span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">U</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">V</span> <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// This is a tuple if you&#39;re not familiar.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">options</span><span style="color:#f92672">:</span> [<span style="color:#a6e22e">T</span>, <span style="color:#a6e22e">U</span>, <span style="color:#a6e22e">V</span>] <span style="color:#f92672">=</span> [
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">one</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">two</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">three</span>
</span></span><span style="display:flex;"><span>    ];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">rndNum</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">getRndNumInInclusiveRange</span>(<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">2</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">options</span>[<span style="color:#a6e22e">rndNum</span>];
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Keep in mind that there is no &ldquo;uniqueness constraint&rdquo; forced on the types - you could pass in any combination you wish, such as two <code>string</code>s and a <code>number</code>, for instance. Additionally, just like the input arguments are &ldquo;in scope&rdquo; for the body of the function, so are the generic type parameters. The former example demonstrates that we have full access to <code>T</code>, <code>U</code>, and <code>V</code> from within the body of the function, and we used them to declare a local 3-tuple.</p>
<p>You can imagine that these generics operate over a certain &ldquo;context&rdquo; or within a certain &ldquo;lifetime&rdquo;, and that depends on where they&rsquo;re declared. Generics on functions are in scope within the function signature and body (and closures created by nested functions), while generics declared on a class or interface or type alias are in scope for all members of the class or interface or type alias.</p>
<p>The notion of generics on functions is not limited to &ldquo;free functions&rdquo; or &ldquo;floating functions&rdquo; (functions not attached to an object or class, a C++ term), but they can also be used on functions attached to other structures, too.</p>
<p>We can place that <code>randomValue</code> in a class and we can call it just the same:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Utils</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">randomValue</span>&lt;<span style="color:#f92672">T</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">U</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">V</span>&gt;(
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">one</span>: <span style="color:#66d9ef">T</span>, 
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">two</span>: <span style="color:#66d9ef">U</span>, 
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">three</span>: <span style="color:#66d9ef">V</span>
</span></span><span style="display:flex;"><span>    )<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">U</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">V</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Or, as an arrow function:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">randomValue</span> <span style="color:#f92672">=</span> &lt;<span style="color:#f92672">T</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">U</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">V</span>&gt;(
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">one</span>: <span style="color:#66d9ef">T</span>, 
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">two</span>: <span style="color:#66d9ef">U</span>, 
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">three</span>: <span style="color:#66d9ef">V</span>
</span></span><span style="display:flex;"><span>    )<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">U</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">V</span> <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>We could also place a definition within an interface:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUtils</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">randomValue</span>&lt;<span style="color:#f92672">T</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">U</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">V</span>&gt;(
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">one</span>: <span style="color:#66d9ef">T</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">two</span>: <span style="color:#66d9ef">U</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">three</span>: <span style="color:#66d9ef">V</span>
</span></span><span style="display:flex;"><span>    )<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">U</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">V</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Or within a type alias:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Utils</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">randomValue</span>&lt;<span style="color:#f92672">T</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">U</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">V</span>&gt;(
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">one</span>: <span style="color:#66d9ef">T</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">two</span>: <span style="color:#66d9ef">U</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">three</span>: <span style="color:#66d9ef">V</span>
</span></span><span style="display:flex;"><span>    )<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">U</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">V</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Just like before, these generic type parameters are &ldquo;in scope&rdquo; for that particular function - they are not class, or interface, or type alias-wide. They live only within the particular function upon which they&rsquo;re specified. To share a generic type across all members of a structure, you must annotate the structure&rsquo;s name itself, as we&rsquo;ll see below.</p>
<h3 id="exploring-generic-syntax---type-aliases">Exploring Generic Syntax - Type Aliases</h3>
<p>With Type Aliases, the generic syntax is used on the alias&rsquo;s name.</p>
<p>For instance, some &ldquo;action&rdquo; function that accepts a value, possibly mutates that value, but returns void could be written as:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Action</span>&lt;<span style="color:#f92672">T</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">val</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>;
</span></span></code></pre></div><blockquote>
<p><em>This should be familiar to C# developers who understand the Action<!-- raw HTML omitted --> delegate.</em></p>
</blockquote>
<p>Or, a callback function that accepts both an error and a value could be declared as such:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CallbackFunction</span>&lt;<span style="color:#f92672">T</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">Error</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">usersApi</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">get</span>(<span style="color:#a6e22e">uri</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">cb</span>: <span style="color:#66d9ef">CallbackFunction</span>&lt;<span style="color:#f92672">User</span>&gt;) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">/// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>With our knowledge of function generics, we could go further and make the function on the API object generic too:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CallbackFunction</span>&lt;<span style="color:#f92672">T</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">Error</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">api</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// `T` is available for use within this function.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">get</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#a6e22e">uri</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">cb</span>: <span style="color:#66d9ef">CallbackFunction</span>&lt;<span style="color:#f92672">T</span>&gt;) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">/// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Now, we&rsquo;re saying that the <code>get</code> function accepts some generic type parameter, and whatever that is, <code>CallbackFunction</code> receives it. We&rsquo;ve essentially &ldquo;passed&rdquo; the <code>T</code> that goes into <code>get</code> as the <code>T</code> for <code>CallbackFunction</code>. Perhaps this would make more sense if we change the names:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CallbackFunction</span>&lt;<span style="color:#f92672">TData</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">Error</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">TData</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">api</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">get</span>&lt;<span style="color:#f92672">TResponse</span>&gt;(<span style="color:#a6e22e">uri</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">cb</span>: <span style="color:#66d9ef">CallbackFunction</span>&lt;<span style="color:#f92672">TResponse</span>&gt;) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Prefixing type params with <code>T</code> is merely a convention, just like prefixing interfaces with <code>I</code> or member variables with <code>_</code>. What you can see here is that <code>CallbackFunction</code> accepts some type (<code>TData</code>) which represents the data payload available to the function, while <code>get</code> accepts a type parameter that represents the HTTP Response data type/shape (<code>TResponse</code>). The HTTP Client (<code>api</code>), similar to Axios, uses whatever that <code>TResponse</code> is as the <code>TData</code> for <code>CallbackFunction</code>. This allows the API caller to select the data type they&rsquo;ll be receiving back from the API (suppose somewhere else in the pipeline we have middleware that parses the JSON into a DTO).</p>
<p>If we wanted to take this a little further, we could modify the generic type parameters on <code>CallbackFunction</code> to accept a custom error type as well:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CallbackFunction</span>&lt;<span style="color:#f92672">TData</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">TError</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">TError</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">TData</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>;
</span></span></code></pre></div><p>And, just like you can make function arguments optional, you can with type parameters too. In the event that the user does not provide an error type, we&rsquo;ll set it to the error constructor by default:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">CallbackFunction</span>&lt;<span style="color:#f92672">TData</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">TError </span><span style="color:#f92672">=</span> <span style="color:#a6e22e">Error</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">TError</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">TData</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>;
</span></span></code></pre></div><p>With this, we can now specify a callback function type in multiple ways:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">apiOne</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// `Error` is used by default for `CallbackFunction`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">get</span>&lt;<span style="color:#f92672">TResponse</span>&gt;(<span style="color:#a6e22e">uri</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">cb</span>: <span style="color:#66d9ef">CallbackFunction</span>&lt;<span style="color:#f92672">TResponse</span>&gt;) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">apiOne</span>.<span style="color:#66d9ef">get</span>&lt;<span style="color:#f92672">string</span>&gt;(<span style="color:#e6db74">&#39;uri&#39;</span>, (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">Error</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">string</span>) <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">apiTwo</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Override the default and use `HttpError` instead.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">get</span>&lt;<span style="color:#f92672">TResponse</span>&gt;(<span style="color:#a6e22e">uri</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">cb</span>: <span style="color:#66d9ef">CallbackFunction</span>&lt;<span style="color:#f92672">TResponse</span><span style="color:#960050;background-color:#1e0010">,</span> <span style="color:#a6e22e">HttpError</span>&gt;) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">apiTwo</span>.<span style="color:#66d9ef">get</span>&lt;<span style="color:#f92672">string</span>&gt;(<span style="color:#e6db74">&#39;uri&#39;</span>, (<span style="color:#a6e22e">err</span>: <span style="color:#66d9ef">HttpError</span>, <span style="color:#a6e22e">data</span>: <span style="color:#66d9ef">string</span>) <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>This idea of default parameters is acceptable across functions, classes, interfaces, etc. - it&rsquo;s not just limited to type aliases. In all the examples we&rsquo;ve seen so far, we could have assigned any type parameter we wanted to a default value. Type Aliases, just like functions, can take as many generic type parameters as you wish.</p>
<h3 id="exploring-generic-syntax---interfaces">Exploring Generic Syntax - Interfaces</h3>
<p>As you&rsquo;ve seen, a generic type parameter can be provided to a function on an interface:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUselessFunctions</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Not generic
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">printHelloWorld</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Generic
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">identity</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#a6e22e">t</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this case, <code>T</code> lives only for the <code>identity</code> function as its input and return type.</p>
<p>We can also make a type parameter available to all members of an interface, just like with classes and type aliases, by specifying that the interface itself accepts a generic. We&rsquo;ll talk about the Repository Pattern a little later when we discuss more complex use cases for generics, so it&rsquo;s alright if you&rsquo;ve never heard of it. The Repository Pattern permits us to abstract away our data storage as to make business logic persistence-agnostic. If you wished to create a generic repository interface that operated on unknown entity types, we could type it as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IRepository</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">entity</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">T</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">updateById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">updated</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">removeById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><blockquote>
<p><em>There are many different thoughts around Repositories, from Martin Fowler&rsquo;s definition to the DDD Aggregate definition. I&rsquo;m merely attempting to show a use case for generics, so I&rsquo;m not too concerned with being fully correct implementation-wise. There&rsquo;s definitely something to be said for not using generic repositories, but we&rsquo;ll talk about that later.</em></p>
</blockquote>
<p>As you can see here, <code>IRepository</code> is an interface that contains methods for storing and retrieving data. It operates on some generic type parameter named <code>T</code>, and <code>T</code> is used as input to <code>add</code> and <code>updateById</code>, as well as the promise resolution result of <code>findById</code>.</p>
<p>Keep in mind that there&rsquo;s a very big difference between accepting a generic type parameter on the interface name as opposed to allowing each function itself to accept a generic type parameter. The former, as we&rsquo;ve done here, ensures that each function within the interface operates on the same type <code>T</code>. That is, for an <code>IRepository&lt;User&gt;</code>, every method that uses <code>T</code> in the interface is now working on <code>User</code> objects. With the latter method, each function would be allowed to work with whatever type it wants. It would be very peculiar to only be able to add <code>User</code>s to the Repository but be able to receive <code>Policies</code> or <code>Orders</code> back, for instance, which is the potential situation we&rsquo;d find ourselves in if we couldn&rsquo;t enforce that the type is uniform across all methods.</p>
<p>A given interface can contain not only a shared type, but also types unique to its members. For instance, if we wanted to mimic an array, we could type an interface like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IArray</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">forEach</span>(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">this</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">map</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">IArray</span>&lt;<span style="color:#f92672">U</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>In this case, both <code>forEach</code> and <code>map</code> have access to <code>T</code> from the interface name. As stated, you can imagine that <code>T</code> is in scope for all members of the interface. Despite that, nothing stops individual functions within from accepting their own type parameters as well. The <code>map</code> function does, with <code>U</code>. Now, <code>map</code> has access to both <code>T</code> and <code>U</code>. We had to name the parameter a different letter, like <code>U</code>, because <code>T</code> is already taken and we don&rsquo;t want a naming collision. Quite like its name, <code>map</code> will &ldquo;map&rdquo; elements of type <code>T</code> within the array to new elements of type <code>U</code>. It maps <code>T</code>s to <code>U</code>s. The return value of this function is the interface itself, now operating on the new type <code>U</code>, so that we can somewhat mimic JavaScript&rsquo;s fluent chainable syntax for arrays.</p>
<p>We&rsquo;ll see an example of the power of Generics and Interfaces shortly when we implement the Repository Pattern and discuss Dependency Injection. Once again, we can accept as many generic parameters as well as select one or more default parameters stacked at the end of an interface.</p>
<h3 id="exploring-generic-syntax---classes">Exploring Generic Syntax - Classes</h3>
<p>Much the same as we can pass a generic type parameter to a type alias, function, or interface, we can pass one or more to a class as well. Upon doing so, that type parameter will be accessible to all members of that class as well as extended base classes or implemented interfaces.</p>
<p>Let&rsquo;s build another collection class, but a little simpler than <code>TypedList</code> above, so that we can see the interop between generic types, interfaces, and members. We&rsquo;ll see an example of passing a type to a base class and interface inheritance a little later.</p>
<p>Our collection will merely support basic CRUD functions in addition to a <code>map</code> and <code>forEach</code> method.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Collection</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">elements</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">elements</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> []) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">elements</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">elem</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">contains</span>(<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">boolean</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">includes</span>(<span style="color:#a6e22e">elem</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">remove</span>(<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">filter</span>(<span style="color:#a6e22e">existing</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">existing</span> <span style="color:#f92672">!==</span> <span style="color:#a6e22e">elem</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">forEach</span>(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">forEach</span>(<span style="color:#a6e22e">func</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">map</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Collection</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>	    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Collection</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">func</span>));
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">stringCollection</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Collection</span>&lt;<span style="color:#f92672">string</span>&gt;();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">stringCollection</span>.<span style="color:#a6e22e">add</span>(<span style="color:#e6db74">&#39;Hello, World!&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">numberCollection</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Collection</span>&lt;<span style="color:#f92672">number</span>&gt;();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">numberCollection</span>.<span style="color:#a6e22e">add</span>(<span style="color:#ae81ff">3.14159</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">aircraftCollection</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Collection</span>&lt;<span style="color:#f92672">IAircraft</span>&gt;();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">aircraftCollection</span>.<span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">myAircraft</span>);
</span></span></code></pre></div><p>Let&rsquo;s discuss what&rsquo;s going on here. The <code>Collection</code> class accepts one generic type parameter named <code>T</code>. That type becomes accessible to all members of the class. We use it to define a private array of type <code>T[]</code>, which we could also have denoted in the form <code>Array&lt;T&gt;</code> (See? Generics again for normal TS array typing). Further, most member functions utilize that <code>T</code> in some way, such as by controlling the types that are added and removed or checking if the collection contains an element.</p>
<p>Finally, as we&rsquo;ve seen before, the <code>map</code> method requires its own generic type parameter. We need to define in the signature of <code>map</code> that some type <code>T</code> is mapped to some type <code>U</code> through a callback function, thus we need a <code>U</code>. That <code>U</code> is unique to that function in particular, which means we could have another function in that class that also accepts some type named <code>U</code>, and that&rsquo;d be fine, because those types are only &ldquo;in scope&rdquo; for their functions and not shared across them, thus there are no naming collisions. What we can&rsquo;t do is have another function that accepts a generic parameter named <code>T</code>, for that&rsquo;d conflict with the <code>T</code> from the class signature.</p>
<p>You can see that when we call the constructor, we pass in the type we want to work with (that is, what type each element of the internal array will be). In the calling code at the bottom of the example, we work with <code>string</code>s, <code>number</code>s, and <code>IAircraft</code>s.</p>
<p>How could we make this work with an interface? What if we have different collection interfaces that we might want to swap out or inject into calling code? To get that level of reduced coupling (low coupling and high cohesion is what we should always aim for), we&rsquo;ll need to depend on an abstraction. Generally, that abstraction will be an interface, but it could also be an abstract class.</p>
<p>Our collection interface will need to be generic, so let&rsquo;s define it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">ICollection</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">t</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">contains</span>(<span style="color:#a6e22e">t</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">boolean</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">remove</span>(<span style="color:#a6e22e">t</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">forEach</span>(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">map</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">ICollection</span>&lt;<span style="color:#f92672">U</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Now, let&rsquo;s suppose we have different kinds of collections. We could have an in-memory collection, one that stores data on disk, one that uses a database, etc. By having an interface, the dependent code can depend upon the abstraction, permitting us to swap out different implementations without affecting the existing code. Here is the in-memory collection.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">InMemoryCollection</span>&lt;<span style="color:#f92672">T</span>&gt; <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">ICollection</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">elements</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">elements</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> []) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">elements</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">elem</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">contains</span>(<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">boolean</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">includes</span>(<span style="color:#a6e22e">elem</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">remove</span>(<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">filter</span>(<span style="color:#a6e22e">existing</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">existing</span> <span style="color:#f92672">!==</span> <span style="color:#a6e22e">elem</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">forEach</span>(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">void</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">forEach</span>(<span style="color:#a6e22e">func</span>);
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">map</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">func</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">elem</span>: <span style="color:#66d9ef">T</span>, <span style="color:#a6e22e">index</span>: <span style="color:#66d9ef">number</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">ICollection</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>	    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">InMemoryCollection</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">elements</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">func</span>));
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The interface describes the public-facing methods and properties that our class is required to implement, expecting you to pass in a concrete type that those methods will operate upon. However, at the time of defining the class, we still don&rsquo;t know what type the API caller will wish to use. Thus, we make the class generic too - that is, <code>InMemoryCollection</code> expects to receive some generic type <code>T</code>, and whatever it is, it&rsquo;s immediately passed to the interface, and the interface methods are implemented using that type.</p>
<p>Calling code can now depend on the interface:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// Using type annotation to be explicit for the purposes of the
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// tutorial.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userCollection</span>: <span style="color:#66d9ef">ICollection</span>&lt;<span style="color:#f92672">User</span>&gt; <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">InMemoryCollection</span>&lt;<span style="color:#f92672">User</span>&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">manageUsers</span>(<span style="color:#a6e22e">userCollection</span>: <span style="color:#66d9ef">ICollection</span>&lt;<span style="color:#f92672">User</span>&gt;) {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">userCollection</span>.<span style="color:#a6e22e">add</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">User</span>());
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>With this, any kind of collection can be passed into the <code>manageUsers</code> function as long as it satisfies the interface. This is useful for testing scenarios - rather than dealing with over-the-top mocking libraries, in unit and integration test scenarios, I can replace my <code>SqlServerCollection&lt;T&gt;</code> (for example) with <code>InMemoryCollection&lt;T&gt;</code> instead and perform <em>state-based assertions</em> instead of interaction-based assertions. This setup makes my tests agnostic to implementation details, which means they are, in turn, less likely to break when refactoring the SUT.</p>
<p>At this point, we should have worked up to the point where we can understand that first <code>TypedList&lt;T&gt;</code> example. Here it is again:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">T</span>[]) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">void</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">value</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">where</span>(<span style="color:#a6e22e">predicate</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">boolean</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">filter</span>(<span style="color:#a6e22e">predicate</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">select</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">selector</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">selector</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">toArray</span>()<span style="color:#f92672">:</span> <span style="color:#a6e22e">T</span>[] {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">U</span>[])<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Perhaps we perform some logic here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values?</span>: <span style="color:#66d9ef">U</span>[])<span style="color:#f92672">:</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span> <span style="color:#f92672">??</span> []);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Other collection functions.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// ..
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>The class itself accepts a generic type parameter named <code>T</code>, and all members of the class are provided access to it. The instance method <code>select</code> and the two static methods <code>from</code> and <code>create</code>, which are builders, accept their own generic type parameter named <code>U</code>.</p>
<p>The <code>create</code> static method permits the construction of a list with optional seed data. It accepts some type named <code>U</code> to be the type of every element in the list as well as an optional array of <code>U</code> elements, typed as <code>U[]</code>. When it calls the list&rsquo;s constructor with <code>new</code>, it passes that type <code>U</code> as the generic parameter to <code>TypedList</code>. This creates a new list where the type of every element is <code>U</code>. It is exactly the same as how we could call the constructor of our collection class earlier with <code>new Collection&lt;SomeType&gt;()</code>. The only difference is that the generic type is now passing through the <code>create</code> method rather than being provided and used at the top-level.</p>
<p>I want to make sure this is really, really clear. I&rsquo;ve stated a few times that we can think about passing around types in a similar way that we do variables. It should already be quite intuitive that we can pass a variable through as many layers of indirection as we please. Forget generics and types for a moment and think about an example of the form:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">MyClass</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">t</span>: <span style="color:#66d9ef">number</span>) {}
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#a6e22e">create</span>(<span style="color:#a6e22e">u</span>: <span style="color:#66d9ef">number</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">MyClass</span>(<span style="color:#a6e22e">u</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myClass</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">MyClass</span>.<span style="color:#a6e22e">create</span>(<span style="color:#ae81ff">2.17</span>);
</span></span></code></pre></div><p>This is very similar to what is happening with the more-involved example, the difference being that we&rsquo;re working on generic type parameters, not variables. Here, <code>2.17</code> becomes the <code>u</code> in <code>create</code>, which ultimately becomes the <code>t</code> in the private constructor.</p>
<p>In the case of generics:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">MyClass</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">constructor</span> () {}
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">U</span>&gt;() {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">MyClass</span>&lt;<span style="color:#f92672">U</span>&gt;();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myClass</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">MyClass</span>.<span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">number</span>&gt;();
</span></span></code></pre></div><p>The <code>U</code> passed to <code>create</code> is ultimately passed in as the <code>T</code> for <code>MyClass&lt;T&gt;</code>. When calling <code>create</code>, we provided <code>number</code> as <code>U</code>, thus now <code>U = number</code>. We put that <code>U</code> (which, again, is just <code>number</code>) into the <code>T</code> for <code>MyClass&lt;T&gt;</code>, so that <code>MyClass&lt;T&gt;</code> effectively becomes <code>MyClass&lt;number&gt;</code>. The benefit of generics is that we&rsquo;re opened up to be able to work with types in this abstract and high-level fashion, similar to how we can normal variables.</p>
<p>The <code>from</code> method constructs a new list that operates on an array of elements of type <code>U</code>. It uses that type <code>U</code>, just like <code>create</code>, to construct a new instance of the <code>TypedList</code> class, now passing in that type <code>U</code> for <code>T</code>.</p>
<p>The <code>where</code> instance method performs a filtering operation based upon a predicate function. There&rsquo;s no mapping happening, thus the types of all elements remain the same throughout. The <code>filter</code> method available on JavaScript&rsquo;s array returns a new array of values, which we pass into the <code>from</code> method. So, to be clear, after we filter out the values that don&rsquo;t satisfy the predicate function, we get an array back containing the elements that do. All those elements are still of type <code>T</code>, which is the original type that the caller passed to <code>create</code> when the list was first created. Those filtered elements get given to the <code>from</code> method, which in turn creates a new list containing all those values, still using that original type <code>T</code>. The reason why we return a new instance of the <code>TypedList</code> class is to be able to chain new method calls onto the return result. This adds an element of &ldquo;immutability&rdquo; to our list.</p>
<p>Hopefully, this all provides you with a more intuitive example of generics in practice, and their reason for existence. Next, we&rsquo;ll look at a few of the more advanced topics.</p>
<h2 id="generic-type-inference">Generic Type Inference</h2>
<p>Throughout this article, in all cases where we&rsquo;ve used generics, we&rsquo;ve explicitly defined the type we&rsquo;re operating on. It&rsquo;s important to note that in most cases, we do not have to explicitly define the type parameter we pass in, for TypeScript can infer the type based on usage.</p>
<p>If I have some function that returns a random number, and I pass the return result of that function to <code>identity</code> from earlier without specifying the type parameter, it will be inferred automatically as <code>number</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// `value` is inferred as type `number`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">value</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">identity</span>(<span style="color:#a6e22e">getRandomNumber</span>());
</span></span></code></pre></div><p>To demonstrate type inference, I&rsquo;ve removed all the technically extraneous type annotations from our <code>TypedList</code> structure earlier, and you can see, from the pictures below, that TSC still infers all types correctly:</p>
<p><code>TypedList</code> without extraneous type declarations:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">TypedList</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">T</span>[]) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">value</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">where</span>(<span style="color:#a6e22e">predicate</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#66d9ef">boolean</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#66d9ef">from</span>(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">filter</span>(<span style="color:#a6e22e">predicate</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">select</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">selector</span><span style="color:#f92672">:</span> (<span style="color:#a6e22e">value</span>: <span style="color:#66d9ef">T</span>) <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">U</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">TypedList</span>.<span style="color:#66d9ef">from</span>(<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">selector</span>));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">toArray() {</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">values</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">from</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values</span>: <span style="color:#66d9ef">U</span>[]) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Perhaps we perform some logic here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TypedList</span>(<span style="color:#a6e22e">values</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#a6e22e">create</span>&lt;<span style="color:#f92672">U</span>&gt;(<span style="color:#a6e22e">values?</span>: <span style="color:#66d9ef">U</span>[]) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TypedList</span>(<span style="color:#a6e22e">values</span> <span style="color:#f92672">??</span> []);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Other collection functions.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// ..
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Based on function return values and based on the input types passed into <code>from</code> and the constructor, TSC understands all type information. On the image below, I&rsquo;ve stitched multiple images together which shows Visual Studio&rsquo;s Code TypeScript&rsquo;s Language Extension (and thus the compiler) inferring all the types:</p>
<p><img src="/understanding-typescript-generics/ts-type-inference.png" alt="TypeScript Generic Type Inference"></p>
<h2 id="generic-constraints">Generic Constraints</h2>
<p>Sometimes, we want to put a constraint around a generic type. Perhaps we can&rsquo;t support every type in existence, but we can support a subset of them. Let&rsquo;s say we want to build a function that returns the length of some collection. As seen above, we could have many different types of arrays/collections, from the default JavaScript <code>Array</code> to our custom ones. How do we let our function know that some generic type has a <code>length</code> property attached to it? Similarly, how do restrict the concrete types we pass into the function to those that contain the data we need? An example such as this one, for instance, would not work:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">getLength</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#a6e22e">collection</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">number</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Error. TS does not know that a type T contains a `length` property.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">collection</span>.<span style="color:#a6e22e">length</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The answer is to utilize Generic Constraints. We can define an interface that describes the properties we need:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IHasLength</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">length</span>: <span style="color:#66d9ef">number</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Now, when defining our generic function, we can constrain the generic type to be one that extends that interface:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">getLength</span>&lt;<span style="color:#f92672">T</span> <span style="color:#a6e22e">extends</span> <span style="color:#a6e22e">IHasLength</span>&gt;(<span style="color:#a6e22e">collection</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#66d9ef">number</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Restricting `collection` to be a type that contains
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// everything within the `IHasLength` interface.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">collection</span>.<span style="color:#a6e22e">length</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="real-world-examples">Real-World Examples</h2>
<p>In the next couple of sections, we&rsquo;ll discuss some real-world examples of generics that create more elegant and easy-to-reason-about code. We&rsquo;ve seen a lot of trivial examples, but I want to discuss some approaches to error handling, data access patterns, and front-end React state/props.</p>
<h2 id="real-world-examples---approaches-to-error-handling">Real-World Examples - Approaches to Error Handling</h2>
<p>JavaScript contains a first-class mechanism for handling errors, as do most programming languages - <code>try</code>/<code>catch</code>. Despite that, I&rsquo;m not a very big fan of how it looks when used. That&rsquo;s not to say I don&rsquo;t use the mechanism, I do, but I tend to try and hide it as much as I can. By abstracting <code>try</code>/<code>catch</code> away, I can also reuse error handling logic across likely-to-fail operations.</p>
<p>Suppose we&rsquo;re building some Data Access Layer. This is a layer of the application that wraps the persistence logic for dealing with the data storage method. If we&rsquo;re performing database operations, and if that database is used across a network, particular DB-specific errors and transient exceptions are likely to occur. Part of the reason for having a dedicated Data Access Layer is to abstract away the database from the business logic. Due to that, we can&rsquo;t be having such DB-specific errors being thrown up the stack and out of this layer. We need to wrap them first.</p>
<p>Let&rsquo;s look at a typical implementation that would use <code>try</code>/<code>catch</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">async</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">queryUser</span>(<span style="color:#a6e22e">userID</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dbUser</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">raw</span>(<span style="color:#e6db74">`
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            SELECT * FROM users WHERE user_id = ?
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">        `</span>, [<span style="color:#a6e22e">userID</span>]);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mapper</span>.<span style="color:#a6e22e">toDomain</span>(<span style="color:#a6e22e">dbUser</span>);
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">switch</span> (<span style="color:#66d9ef">true</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">DbErrorOne</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">WrapperErrorOne</span>());
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">DbErrorTwo</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">WrapperErrorTwo</span>());
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">NetworkError</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TransientException</span>());
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">default</span><span style="color:#f92672">:</span>
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">UnknownError</span>());
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Switching over <code>true</code> is just a trick to be able to use the switch <code>case</code> statements for my error checking logic as opposed to having to declare a chain of if/else if.</p>
<p>If we have multiple such functions, we have to replicate this error-wrapping logic, which is a very bad practice. It looks quite good for one function, but it&rsquo;ll be a nightmare with many. To abstract away this logic, we can wrap it in a custom error handling function that will pass through the result, but catch and wrap any errors should they be thrown:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">async</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">withErrorHandling</span>&lt;<span style="color:#f92672">T</span>&gt;(
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">dalOperation</span><span style="color:#f92672">:</span> () <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">T</span>&gt;
</span></span><span style="display:flex;"><span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// This unwraps the promise and returns the type `T`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">dalOperation</span>();
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">switch</span> (<span style="color:#66d9ef">true</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">DbErrorOne</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">WrapperErrorOne</span>());
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">DbErrorTwo</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">WrapperErrorTwo</span>());
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">NetworkError</span>:
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">TransientException</span>());
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">default</span><span style="color:#f92672">:</span>
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">UnknownError</span>());
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>To ensure this makes sense, we have a function entitled <code>withErrorHandling</code> that accepts some generic type parameter <code>T</code>. This <code>T</code> represents the type of the successful resolution value of the promise we expect returned from the <code>dalOperation</code> callback function. Usually, since we&rsquo;re just returning the return result of the async <code>dalOperation</code> function, we wouldn&rsquo;t need to <code>await</code> it for that would wrap the function in a second extraneous promise, and we could leave the <code>await</code>ing to the calling code. In this case, we need to catch any errors, thus <code>await</code> is required.</p>
<p>We can now use this function to wrap our DAL operations from earlier:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">async</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">queryUser</span>(<span style="color:#a6e22e">userID</span>: <span style="color:#66d9ef">string</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">withErrorHandling</span>&lt;<span style="color:#f92672">User</span>&gt;(<span style="color:#66d9ef">async</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dbUser</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">raw</span>(<span style="color:#e6db74">`
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            SELECT * FROM users WHERE user_id = ?
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">        `</span>, [<span style="color:#a6e22e">userID</span>]);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mapper</span>.<span style="color:#a6e22e">toDomain</span>(<span style="color:#a6e22e">dbUser</span>);
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>And there we go. We have a type-safe and error-safe function user query function.</p>
<p>Additionally, as you saw earlier, if the TypeScript Compiler has enough information to infer the types implicitly, you don&rsquo;t have to explicitly pass them. In this case, TSC knows that the return result of the function is what the generic type is. Thus, if <code>mapper.toDomain(user)</code> returned a type of <code>User</code>, you wouldn&rsquo;t need to pass the type in at all:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">async</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">queryUser</span>(<span style="color:#a6e22e">userID</span>: <span style="color:#66d9ef">string</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">withErrorHandling</span>(<span style="color:#66d9ef">async</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dbUser</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">raw</span>(<span style="color:#e6db74">`
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            SELECT * FROM users WHERE user_id = ?
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">        `</span>, [<span style="color:#a6e22e">userID</span>]);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mapper</span>.<span style="color:#a6e22e">toDomain</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Another approach to error handling that I tend to like is that of Monadic Types. The Either Monad is an algebraic data type of the form <code>Either&lt;T, U&gt;</code>, where <code>T</code> can represent an error type, and <code>U</code> can represent a failure type. Using Monadic Types hearkens to functional programming, and a major benefit is that errors become type-safe - a normal function signature doesn&rsquo;t tell the API caller anything about what errors that function might throw. Suppose we throw a <code>NotFound</code> error from inside <code>queryUser</code>. A signature of <code>queryUser(userID: string): Promise&lt;User&gt;</code> doesn&rsquo;t tell us anything about that. But, a signature like <code>queryUser(userID: string): Promise&lt;Either&lt;NotFound, User&gt;&gt;</code> absolutely does. I won&rsquo;t explain how monads like the Either Monad work in this article because they can be quite complex, and there are a variety of methods they must have to be considered monadic, such as mapping/binding. If you’d like to learn more about them, I’d recommend two of Scott Wlaschin’s NDC talks, <a href="https://www.youtube.com/watch?v=Nrp_LZ-XGsY">here</a> and <a href="https://www.youtube.com/watch?v=srQt1NAHYC0">here</a>, as well as Daniel Chamber’s talk <a href="https://www.youtube.com/watch?v=v9QGWbGppis">here</a>. <a href="http://learnyouahaskell.com/a-fistful-of-monads">This</a> site as well <a href="https://ericlippert.com/category/monads/">these</a> blog posts may be useful too.</p>
<h2 id="real-world-examples---repository-pattern">Real-World Examples - Repository Pattern</h2>
<p>Let&rsquo;s take a look at another use case where Generics might be helpful. Most back-end systems are required to interface with a database in some manner - this could be a relational database like PostgreSQL, a document database like MongoDB, or perhaps even a graph database, such as Neo4j.</p>
<p>Since, as developers, we should aim for lowly coupled and highly cohesive designs, it would be a fair argument to consider what the ramifications of migrating database systems might be. It would also be fair to consider that different data access needs might prefer different data access approaches (this starts to get into CQRS a little bit, which is a pattern for separating reads and writes. See <a href="https://martinfowler.com/bliki/CQRS.html">Martin Fowler’s</a> post and the <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/apply-simplified-microservice-cqrs-ddd-patterns#:~:text=CQRS%20is%20an%20architectural%20pattern,book%20Object%20Oriented%20Software%20Construction.">MSDN listing</a> if you wish to learn more. The books “Implementing Domain Driven Design” by Vaughn Vernon and “Patterns, Principles, and Practices of Domain-Driven Design” by Scott Millet are good reads as well). We should also consider automated testing. The majority of tutorials that explain the building of back-end systems with Node.js intermingle data access code with business logic with routing. That is, they tend to use MongoDB with the Mongoose ODM, taking an Active Record approach, and not having a clean separation of concerns. Such techniques are frowned upon in large applications, for the moment you decide you&rsquo;d like to migrate one database system for another, or the moment you realize that you&rsquo;d prefer a different approach to data access, etc., you have to rip out that old data access code, replace it with new code, and hope you didn&rsquo;t introduce any bugs to routing and business logic along the way.</p>
<p>Sure, you might argue that unit and integration tests will prevent regressions, but if those tests find themselves coupled and dependent upon implementation details to which they should be agnostic, they too will likely break in the process.</p>
<p>A common approach to solve this issue is the <a href="https://martinfowler.com/eaaCatalog/repository.html">Repository Pattern</a>. It says that to calling code, we should allow our data access layer to mimic a mere in-memory collection of objects or domain entities. In this way, we can let the business drive the design rather than the database (data model). For large applications, an architectural pattern called Domain-Driven Design becomes useful. Repositories, in the Repository Pattern, are components, most commonly classes, that encapsulate and hold internal all the logic to access data sources. With this, we can centralize data access code to one layer, making it easily testable and easily reusable. Further, we can place a mapping layer in between, permitting us to map database-agnostic domain models to a series of one-to-one table mappings. Each function available on the Repository could optionally use a different data access method if you so choose.</p>
<p>There are many different approaches and semantics to Repositories, Units of Work, database transactions across tables, etc. Since this is an article about Generics, I don&rsquo;t want to get into the weeds too much, thus I&rsquo;ll illustrate a simple example here, but it&rsquo;s important to note that different applications have different needs. A Repository for DDD Aggregates would be quite different than what we&rsquo;re doing here, for instance. How I portray the Repository implementations here is not how I implement them in real projects, for there is a lot of missing functionality and less-than-desired architectural practices in use.</p>
<p>Let&rsquo;s suppose we have <code>Users</code> and <code>Tasks</code> as domain models. These could just be POTOs - Plain-Old TypeScript Objects. There is no notion of a database baked into them, thus, you wouldn&rsquo;t call <code>User.save()</code>, for instance, as you would using Mongoose. Using the Repository Pattern, we might persist a user or delete a task from our business logic as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#75715e">// Querying the DB for a User by their ID.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span>: <span style="color:#66d9ef">User</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">userID</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Deleting a Task by its ID.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">await</span> <span style="color:#a6e22e">taskRepository</span>.<span style="color:#a6e22e">deleteById</span>(<span style="color:#a6e22e">taskID</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Deleting a Task by its owner&#39;s ID.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">await</span> <span style="color:#a6e22e">taskRepository</span>.<span style="color:#a6e22e">deleteByUserId</span>(<span style="color:#a6e22e">userID</span>);
</span></span></code></pre></div><p>Clearly, you can see how all the messy and transient data access logic is hidden behind this repository facade/abstraction, making business logic agnostic to persistence concerns.</p>
<p>Let&rsquo;s start by building a few simple domain models. These are the models that the application code will interact with. They are anemic here but would hold their own logic to satisfy business invariants in the real-world, that is, they wouldn&rsquo;t be mere data bags.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IHasIdentity</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">User</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IHasIdentity</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">_id</span>: <span style="color:#66d9ef">string</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">_username</span>: <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>    ) {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">get</span> <span style="color:#a6e22e">id() {</span> <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">_id</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">get</span> <span style="color:#a6e22e">username() {</span> <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">_username</span>; }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Task</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IHasIdentity</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">_id</span>: <span style="color:#66d9ef">string</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">_title</span>: <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>    ) {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">get</span> <span style="color:#a6e22e">id() {</span> <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">_id</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">get</span> <span style="color:#a6e22e">title() {</span> <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">_title</span>; }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>You&rsquo;ll see in a moment why we extract identity typing information to an interface. This method of defining domain models and passing everything through the constructor is not how I&rsquo;d do it in the real world. Additionally, relying on an abstract domain model class would have been more preferable than the interface to get the <code>id</code> implementation for free.</p>
<p>For the Repository, since, in this case, we expect that many of the same persistence mechanisms will be shared across different domain models, we can abstract our Repository methods to a generic interface:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IRepository</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">entity</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">T</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">updateById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">updated</span>: <span style="color:#66d9ef">T</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">deleteById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">void</span>&gt;;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">existsById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>We could go further and create a Generic Repository too to reduce duplication. For brevity, I won&rsquo;t do that here, and I should note that Generic Repository interfaces such as this one and Generic Repositories, in general, tend to be frowned upon, for you might have certain entities which are read-only, or write-only, or which can&rsquo;t be deleted, etc. It depends on the application. Also, we don&rsquo;t have a notion of a &ldquo;unit of work&rdquo; in order to share a transaction across tables, a feature I would implement in the real world, but, again, since this is a small demo, I don&rsquo;t want to get too technical.</p>
<p>Let&rsquo;s start by implementing our <code>UserRepository</code>. I&rsquo;ll define an <code>IUserRepository</code> interface which holds methods specific to users, thus permitting calling code to depend on that abstraction when we dependency inject the concrete implementations:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUserRepository</span> <span style="color:#66d9ef">extends</span> <span style="color:#a6e22e">IRepository</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">existsByUsername</span>(<span style="color:#a6e22e">username</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserRepository</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IUserRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// There are 6 methods to implement here all using the 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// concrete type of `User` - Five from IRepository&lt;User&gt;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// and the one above.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>The Task Repository would be similar but would contain different methods as the application sees fit.</p>
<p>Here, we&rsquo;re defining an interface that extends a generic one, thus we have to pass the concrete type we&rsquo;re working on. As you can see from both interfaces, we have the notion that we send these POTO domain models in and we get them out. The calling code has no idea what the underlying persistence mechanism is, and that&rsquo;s the point.</p>
<p>The next consideration to make is that depending on the data access method we choose, we&rsquo;ll have to handle database-specific errors. We could place Mongoose or the Knex Query Builder behind this Repository, for example, and in that case, we&rsquo;ll have to handle those specific errors - we don&rsquo;t want them to bubble up to business logic for that would break separation of concerns and introduce a larger degree of coupling.</p>
<p>Let&rsquo;s define a Base Repository for the data access methods we wish to use that can handle errors for us:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">BaseKnexRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// A constructor.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    
</span></span><span style="display:flex;"><span>     <span style="color:#75715e">/**
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     * Wraps a likely to fail database operation within a function that handles errors by catching
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     * them and wrapping them in a domain-safe error.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     * 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     * @param dalOp The operation to perform upon the database. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     */</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">withErrorHandling</span>&lt;<span style="color:#f92672">T</span>&gt;(<span style="color:#a6e22e">dalOp</span><span style="color:#f92672">:</span> () <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">T</span>&gt;) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">dalOp</span>();
</span></span><span style="display:flex;"><span>        } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Use a proper logger:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>            <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">error</span>(<span style="color:#a6e22e">e</span>);
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Handle errors properly here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Now, we can extend this Base Class in the Repository and access that Generic method:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUserRepository</span> <span style="color:#66d9ef">extends</span> <span style="color:#a6e22e">IRepository</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">existsByUsername</span>(<span style="color:#a6e22e">username</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt;;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserRepository</span> <span style="color:#66d9ef">extends</span> <span style="color:#a6e22e">BaseKnexRepository</span> <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IUserRepository</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">dbContext</span>: <span style="color:#66d9ef">Knex</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">Knex</span>.<span style="color:#a6e22e">Transaction</span>;
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (<span style="color:#66d9ef">private</span> <span style="color:#a6e22e">knexInstance</span>: <span style="color:#66d9ef">Knex</span> <span style="color:#f92672">|</span> <span style="color:#a6e22e">Knex</span>.<span style="color:#a6e22e">Transaction</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">super</span>();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">dbContext</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">knexInstance</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Example `findById` implementation:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">withErrorHandling</span>&lt;<span style="color:#f92672">User</span>&gt;(<span style="color:#66d9ef">async</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">dbUser</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">dbContext</span>&lt;<span style="color:#f92672">DbUser</span>&gt;()
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">select</span>()
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">where</span>({ <span style="color:#a6e22e">user_id</span>: <span style="color:#66d9ef">id</span> })
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">first</span>();
</span></span><span style="display:flex;"><span>                
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Maps type DbUser to User    
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mapper</span>.<span style="color:#a6e22e">toDomain</span>(<span style="color:#a6e22e">dbUser</span>);
</span></span><span style="display:flex;"><span>        });
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// There are 5 methods to implement here all using the 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// concrete type of `User`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Notice that our function retrieves a <code>DbUser</code> from the database and maps it to a <code>User</code> domain model before returning it. This is the Data Mapper pattern and it&rsquo;s crucial to maintaining separation of concerns. <code>DbUser</code> is a one-to-one mapping to the database table - it&rsquo;s the data model that the Repository operates upon - and is thus highly dependent on the data storage technology used. For this reason, <code>DbUser</code>s will never leave the Repository and will be mapped to a <code>User</code> domain model before being returned. I didn&rsquo;t show the <code>DbUser</code> implementation, but it could just be a simple class or interface.</p>
<p>Thus far, using the Repository Pattern, powered by Generics, we&rsquo;ve managed to abstract away data access concerns into small units as well as maintain type-safety and re-usability.</p>
<p>Finally, for the purposes of Unit and Integration Testing, let&rsquo;s say that we&rsquo;ll keep an in-memory repository implementation so that in a test environment, we can inject that repository, and perform state-based assertions on disk rather than mocking with a mocking framework. This method forces everything to rely on the public-facing interfaces rather than permitting tests to be coupled to implementation details. Since the only differences between each repository are the methods they choose to add under the <code>ISomethingRepository</code> interface, we can build a generic in-memory repository and extend that within type-specific implementations:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">InMemoryRepository</span>&lt;<span style="color:#f92672">T</span> <span style="color:#a6e22e">extends</span> <span style="color:#a6e22e">IHasIdentity</span>&gt; <span style="color:#66d9ef">implements</span> <span style="color:#a6e22e">IRepository</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">protected</span> <span style="color:#a6e22e">entities</span>: <span style="color:#66d9ef">T</span>[] <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">T</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">entityOrNone</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">entities</span>.<span style="color:#a6e22e">find</span>(<span style="color:#a6e22e">entity</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">entity</span>.<span style="color:#a6e22e">id</span> <span style="color:#f92672">===</span> <span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">entityOrNone</span> 
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">?</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">resolve</span>(<span style="color:#a6e22e">entityOrNone</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>.<span style="color:#a6e22e">reject</span>(<span style="color:#66d9ef">new</span> <span style="color:#a6e22e">NotFound</span>());
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Implement the rest of the IRepository&lt;T&gt; methods here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>The purpose of this base class is to perform all the logic for handling in-memory storage so that we don&rsquo;t have to duplicate it within in-memory test repositories. Due to methods like <code>findById</code>, this repository has to have an understanding that entities contain an <code>id</code> field, which is why the generic constraint on the <code>IHasIdentity</code> interface is necessary. We saw this interface before - it&rsquo;s what our domain models implemented.</p>
<p>With this, when it comes to building the in-memory user or task repository, we can just extend this class and get most of the methods implemented automatically:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">InMemoryUserRepository</span> <span style="color:#66d9ef">extends</span> <span style="color:#a6e22e">InMemoryRepository</span>&lt;<span style="color:#f92672">User</span>&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">existsByUsername</span>(<span style="color:#a6e22e">username</span>: <span style="color:#66d9ef">string</span>)<span style="color:#f92672">:</span> <span style="color:#a6e22e">Promise</span>&lt;<span style="color:#f92672">boolean</span>&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userOrNone</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">entities</span>.<span style="color:#a6e22e">find</span>(<span style="color:#a6e22e">entity</span> <span style="color:#f92672">=&gt;</span> <span style="color:#a6e22e">entity</span>.<span style="color:#a6e22e">username</span> <span style="color:#f92672">===</span> <span style="color:#a6e22e">username</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> Boolean(<span style="color:#a6e22e">userOrNone</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// or, return !!userOrNone;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    }
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// And that&#39;s it here. InMemoryRepository implements the rest.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Here, our <code>InMemoryRepository</code> needs to know that entities have fields such as <code>id</code> and <code>username</code>, thus we pass <code>User</code> as the generic parameter. <code>User</code> already implements <code>IHasIdentity</code>, so the generic constraint is satisfied, and we also state that we have a <code>username</code> property too.</p>
<p>Now, when we wish to use these repositories from the Business Logic Layer, it&rsquo;s quite simple:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">UserService</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">constructor</span> (
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">userRepository</span>: <span style="color:#66d9ef">IUserRepository</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> <span style="color:#a6e22e">emailService</span>: <span style="color:#66d9ef">IEmailService</span>
</span></span><span style="display:flex;"><span>    ) {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> <span style="color:#a6e22e">createUser</span>(<span style="color:#a6e22e">dto</span>: <span style="color:#66d9ef">ICreateUserDTO</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Validate the DTO:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Create a User Domain Model from the DTO
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">userFactory</span>(<span style="color:#a6e22e">dto</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Persist the Entity
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">userRepository</span>.<span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span> 
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Send a welcome email
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">emailService</span>.<span style="color:#a6e22e">sendWelcomeEmail</span>(<span style="color:#a6e22e">user</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>(Note that in a real application, we&rsquo;d probably move the call to <code>emailService</code> to a job queue as to not add latency to the request and in the hopes of being able to perform idempotent retries on failures (- not that email sending is particularly idempotent in the first place). Further, passing the whole user object to the service is questionable too. The other issue to note is that we could find ourselves in a position here where the server crashes after the user is persisted but before the email is sent. There are mitigation patterns to prevent this, but for the purposes of pragmatism, human intervention with proper logging will probably work just fine).</p>
<p>And there we go - using the Repository Pattern with the power of Generics, we&rsquo;ve completely decoupled our DAL from our BLL and have managed to interface with our repository in a type-safe manner. We&rsquo;ve also developed a way to rapidly construct equally type-safe in-memory repositories for the purposes of unit and integration testing, permitting true black-box and implementation-agnostic tests. None of this would have been possible without Generic types.</p>
<p>As a disclaimer, I want to once again note that this Repository implementation is lacking in a lot. I wanted to keep the example simple since the focus is the utilization of generics, which is why I didn&rsquo;t handle the duplication or worry about transactions. Decent repository implementations would take an article all by themselves to explain fully and correctly, and the implementation details change depending on whether you&rsquo;re doing N-Tier Architecture or DDD. That means that if you wish to use the Repository Pattern, you should <strong>not</strong> look at my implementation here as in any way a best practice.</p>
<h2 id="real-world-examples---react-state--props">Real-World Examples - React State &amp; Props</h2>
<p>The state, ref, etc., hooks for React Functional Components are Generic too. If I have an interface containing properties for <code>Task</code>s, and I want to hold a collection of them in a React Component, I could do so as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-tsx" data-lang="tsx"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> <span style="color:#a6e22e">React</span>, { <span style="color:#a6e22e">useState</span> } <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;react&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">MyComponent</span>: <span style="color:#66d9ef">React.FC</span> <span style="color:#f92672">=</span> () <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// An empty array of tasks as the initial state:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> [<span style="color:#a6e22e">tasks</span>, <span style="color:#a6e22e">setTasks</span>] <span style="color:#f92672">=</span> <span style="color:#a6e22e">useState</span>&lt;<span style="color:#f92672">Task</span><span style="color:#960050;background-color:#1e0010">[]</span>&gt;([]);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// A counter:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// Notice, type of `number` is inferred automatically.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> [<span style="color:#a6e22e">counter</span>, <span style="color:#a6e22e">setCounter</span>] <span style="color:#f92672">=</span> <span style="color:#a6e22e">useState</span>(<span style="color:#ae81ff">0</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> (
</span></span><span style="display:flex;"><span>        &lt;<span style="color:#f92672">div</span>&gt;
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">h3</span>&gt;<span style="color:#a6e22e">Counter</span> <span style="color:#a6e22e">Value</span><span style="color:#f92672">:</span> {<span style="color:#a6e22e">counter</span>}&lt;/<span style="color:#f92672">h3</span>&gt;
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">ul</span>&gt;
</span></span><span style="display:flex;"><span>                {
</span></span><span style="display:flex;"><span>                    <span style="color:#a6e22e">tasks</span>.<span style="color:#a6e22e">map</span>(<span style="color:#a6e22e">task</span> <span style="color:#f92672">=&gt;</span> (
</span></span><span style="display:flex;"><span>                        &lt;<span style="color:#f92672">li</span> <span style="color:#a6e22e">key</span><span style="color:#f92672">=</span>{<span style="color:#a6e22e">task</span>.<span style="color:#a6e22e">id</span>}&gt;
</span></span><span style="display:flex;"><span>                            &lt;<span style="color:#f92672">TaskItem</span> {<span style="color:#a6e22e">...task</span>}/&gt;
</span></span><span style="display:flex;"><span>                        &lt;/<span style="color:#f92672">li</span>&gt;
</span></span><span style="display:flex;"><span>                    ))
</span></span><span style="display:flex;"><span>                }
</span></span><span style="display:flex;"><span>            &lt;/<span style="color:#f92672">ul</span>&gt;
</span></span><span style="display:flex;"><span>        &lt;/<span style="color:#f92672">div</span>&gt;
</span></span><span style="display:flex;"><span>    );
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>Additionally, if we want to pass a series of props into our function, we can use the generic <code>React.FC&lt;T&gt;</code> type and get access to <code>props</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-tsx" data-lang="tsx"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> <span style="color:#a6e22e">React</span> <span style="color:#66d9ef">from</span> <span style="color:#e6db74">&#39;react&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IProps</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">id</span>: <span style="color:#66d9ef">string</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">title</span>: <span style="color:#66d9ef">string</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">description</span>: <span style="color:#66d9ef">string</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">TaskItem</span>: <span style="color:#66d9ef">React.FC</span>&lt;<span style="color:#f92672">IProps</span>&gt; <span style="color:#f92672">=</span> (<span style="color:#a6e22e">props</span>) <span style="color:#f92672">=&gt;</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> (
</span></span><span style="display:flex;"><span>        &lt;<span style="color:#f92672">div</span>&gt;
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">h3</span>&gt;{<span style="color:#a6e22e">props</span>.<span style="color:#a6e22e">title</span>}&lt;/<span style="color:#f92672">h3</span>&gt;
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">p</span>&gt;{<span style="color:#a6e22e">props</span>.<span style="color:#a6e22e">description</span>}&lt;/<span style="color:#f92672">p</span>&gt;
</span></span><span style="display:flex;"><span>        &lt;/<span style="color:#f92672">div</span>&gt;
</span></span><span style="display:flex;"><span>    );
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>The type of <code>props</code> is inferred automatically to be <code>IProps</code> by the TS Compiler.</p>
<h2 id="conclusion">Conclusion</h2>
<p>In this article, we&rsquo;ve seen many different examples of Generics and their use cases, from simple collections, to error handling approaches, to data access layer isolation, etc. In the simplest of terms, Generics permit us to build data structures without needing to know the concrete time upon which they will operate at compile-time. Hopefully, this helps to open up the subject a little more, make the notion of Generics a little bit more intuitive, and bring across their true power.</p>
]]></content>
        </item>
        
        <item>
            <title>Test Katex Integration</title>
            <link>/2020/09/test-katex-integration/</link>
            <pubDate>Tue, 15 Sep 2020 18:19:12 -0500</pubDate>
            
            <guid>/2020/09/test-katex-integration/</guid>
            <description>An nth Partial Sum:
$$ \sum_{i=1}^n i = \frac{n(n+1)}{2} $$
A code example:
int main(int argc, char *argv[]) { int count = 0; int max = argv[1]; for (int i = 1; i &amp;lt;= max; i++) { count += i; } std::cout &amp;lt;&amp;lt; &amp;#34;Sum: &amp;#34; &amp;lt;&amp;lt; count &amp;lt;&amp;lt; std::endl; } Product $\prod_{i=a}^{b} f(i)$ inside text.
A chemical formula:
$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$
A little bit more complex:</description>
            <content type="html"><![CDATA[<p>An nth Partial Sum:</p>
<p>$$
\sum_{i=1}^n i = \frac{n(n+1)}{2}
$$</p>
<p>A code example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-cpp" data-lang="cpp"><span style="display:flex;"><span><span style="color:#66d9ef">int</span> <span style="color:#a6e22e">main</span>(<span style="color:#66d9ef">int</span> argc, <span style="color:#66d9ef">char</span> <span style="color:#f92672">*</span>argv[]) 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">int</span> count <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>;
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">int</span> max <span style="color:#f92672">=</span> argv[<span style="color:#ae81ff">1</span>];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> <span style="color:#ae81ff">1</span>; i <span style="color:#f92672">&lt;=</span> max; i<span style="color:#f92672">++</span>) 
</span></span><span style="display:flex;"><span>	{
</span></span><span style="display:flex;"><span>		count <span style="color:#f92672">+=</span> i;
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	
</span></span><span style="display:flex;"><span>	std<span style="color:#f92672">::</span>cout <span style="color:#f92672">&lt;&lt;</span> <span style="color:#e6db74">&#34;Sum: &#34;</span> <span style="color:#f92672">&lt;&lt;</span> count <span style="color:#f92672">&lt;&lt;</span> std<span style="color:#f92672">::</span>endl;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Product $\prod_{i=a}^{b} f(i)$ inside text.</p>
<p>A chemical formula:</p>
<p>$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$</p>
<p>A little bit more complex:</p>
<p>$\ce{Zn^2+  &lt;=&gt;[+ 2OH-][+ 2H+]  $\underset{\text{amphoteres Hydroxid}}{\ce{Zn(OH)2 v}}$  &lt;=&gt;[+ 2OH-][+ 2H+]  $\underset{\text{Hydroxozikat}}{\ce{[Zn(OH)4]^2-}}$}$</p>
<p>This is fun.</p>
]]></content>
        </item>
        
        <item>
            <title>Getting Started With An Express And ES6&#43; JavaScript Stack</title>
            <link>/2019/11/getting-started-with-an-express-and-es6-javascript-stack/</link>
            <pubDate>Fri, 22 Nov 2019 14:27:44 -0500</pubDate>
            
            <guid>/2019/11/getting-started-with-an-express-and-es6-javascript-stack/</guid>
            <description>This article was first written for Smashing Magazine on November 22nd, 2019. You can find it here.
This article is the second part in a series, with part one located here, which provided basic and (hopefully) intuitive insight into Node.js, ES6+ JavaScript, Callback Functions, Arrow Functions, APIs, the HTTP Protocol, JSON, MongoDB, and more.
In this article, we&amp;rsquo;ll build upon the skills we attained in the previous one, learning how to implement and deploy a MongoDB Database for storing user booklist information, build an API with Node.</description>
            <content type="html"><![CDATA[<blockquote>
<p>This article was first written for Smashing Magazine on November 22nd, 2019. You can find it <a href="https://www.smashingmagazine.com/2019/11/express-es6-javascript-stack-mongodb-mongoose-servers/">here</a>.</p>
</blockquote>
<p>This article is the second part in a series, with part one located <a href="/posts/introduction-to-node/">here</a>, which provided basic and (hopefully) intuitive insight into Node.js, ES6+ JavaScript, Callback Functions, Arrow Functions, APIs, the HTTP Protocol, JSON, MongoDB, and more.</p>
<p>In this article, we&rsquo;ll build upon the skills we attained in the previous one, learning how to implement and deploy a MongoDB Database for storing user booklist information, build an API with Node.js and the Express Web Application framework to expose that database and perform CRUD Operations upon it, and more. Along the way, we&rsquo;ll discuss ES6 Object Destructuring, ES6 Object Shorthand, the Async/Await syntax, the Spread Operator, and we&rsquo;ll take a brief look at CORS, the Same Origin Policy, and more. In a later article, we&rsquo;ll refactor our codebase as to separate concerns by utilizing three-layer architecture and achieving Inversion of Control via Dependency Injection, we&rsquo;ll perform JSON Web Token and Firebase Authentication based security and access control, learn how to securely store passwords, and employ AWS Simple Storage Service to store user avatars with Node.js Buffers and Streams - all the while utilizing PostgreSQL for data persistence. Along the way, we will re-write our codebase from the ground up in TypeScript as to examine Classical OOP concepts - like Polymorphism, Inheritance, Composition, etc., and even design patterns like Factories and Adapters.</p>
<h3 id="a-word-of-warning">A Word of Warning</h3>
<p>There is a problem with the majority of articles discussing Node.js out there today. Most of them, not all of them, go no further than depicting how to setup Express Routing, integrate Mongoose, and perhaps utilize JSON Web Token Authentication. The problem is, they don&rsquo;t talk about architecture, or security best practices, or about clean coding principles, or ACID Compliance, Relational Databases, Fifth Normal Form, the CAP Theorem, Transactions, etc. It&rsquo;s either assumed that you know about all of that coming in, or that you won&rsquo;t be building projects large or popular enough to warrant that aforementioned knowledge. There appear to be a few different types of Node developers - among others, some are new to programming in general, and others come from a long history of enterprise development with C# and the .NET Framework or the Java Spring Framework. The majority of articles cater to the former group. In this article, I&rsquo;m going to do exactly what I just said that too many articles are doing, but in a follow up article, we are going to refactor our codebase entirely, permitting me to explain principles such as Dependency Injection, Three-Layer Architecture (Controller/Service/Repository), Data Mapping and Active Record, design patterns, unit, integration, and mutation testing, SOLID Principles,  Unit of Work, coding against interfaces, security best practices like HSTS, CSRF, NoSQL and SQL Injection Prevention, etc. We will also migrate from MongoDB to PostgreSQL, using the simple query builder Knex instead of an ORM - permitting us to build our own data access infrastructure and to get close up and personal with the Structured Query Language, the different types of relations (One-to-One, Many-to-Many, etc.), and more. This article, then, should appeal to beginners, but the next few should cater to more intermediate developers looking to improve their architecture.</p>
<p>In this one, we are only going to worry about persisting book data. We won&rsquo;t handle user authentication, password hashing, architecture, or anything complex like that. All of that will come in the next and future articles. For now, and very basically, we&rsquo;ll just build a method by which to permit a client to communicate with our web server via the HTTP Protocol as to save book information in a database. I&rsquo;ve intentionally kept it extremely simple and perhaps not all that practical here because this article, in and of itself, is extremely long, for I have taken the liberty of deviating to discuss supplemental topics. Thus, we will progressively improve the quality and complexity of the API over this series, but again, because I&rsquo;m considering this as one of your first introductions to Express, I&rsquo;m intentionally keeping things extremely simple.</p>
<h3 id="es6-object-destructuring">ES6 Object Destructuring</h3>
<p>ES6 Object Destructuring, or Destructuring Assignment Syntax, is a method by which to extract or unpack values from arrays or objects into their own variables. We&rsquo;ll start with object properties and then discuss array elements.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Richard P. Feynman&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Theoretical Physicist&#39;</span> 
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Log properties:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Name:&#39;</span>, <span style="color:#a6e22e">person</span>.<span style="color:#a6e22e">name</span>); 
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Occupation:&#39;</span>, <span style="color:#a6e22e">person</span>.<span style="color:#a6e22e">occupation</span>); 
</span></span></code></pre></div><p>Such an operation is quite primitive, but it can be somewhat of a hassle considering we have to keep referencing <code>person.something</code> everywhere. Suppose there were 10 other places throughout our code where we had to do that - it would get quite arduous quite fast. A method of brevity would be to assign these values to their own variables.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Richard P. Feynman&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Theoretical Physicist&#39;</span> 
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">personName</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>.<span style="color:#a6e22e">name</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">personOccupation</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>.<span style="color:#a6e22e">occupation</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Log properties:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Name:&#39;</span>, <span style="color:#a6e22e">personName</span>); 
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Occupation:&#39;</span>, <span style="color:#a6e22e">personOccupation</span>); 
</span></span></code></pre></div><p>Perhaps this looks reasonable, but what if we had 10 other properties nested on the <code>person</code> object as well? That would be many needless lines just to assign values to variables - at which point we&rsquo;re in danger because if object properties are mutated, our variables won&rsquo;t reflect that change (remember, only references to the object are immutable with <code>const</code> assignment, not the object&rsquo;s properties), so basically, we can no longer keep &ldquo;state&rdquo; (and I&rsquo;m using that word loosely) in sync. Pass by reference vs pass by value might come into play here, but I don&rsquo;t want to stray too far from the scope of this section.</p>
<p>ES6 Object Destructing basically lets us do this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Richard P. Feynman&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Theoretical Physicist&#39;</span> 
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is new. It&#39;s called Object Destructuring.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">occupation</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Log properties:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Name:&#39;</span>, <span style="color:#a6e22e">name</span>); 
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Occupation:&#39;</span>, <span style="color:#a6e22e">occupation</span>); 
</span></span></code></pre></div><p>We are <strong>not</strong> creating a new object/object literal, we are unpacking the <code>name</code> and <code>occupation</code> properties from the original object and putting them into their own variables of the same name. The names we use have to match the property names that we wish to extract.</p>
<p>Again, the syntax <code>const { a, b } = someObject;</code>  is specifically saying that we expect some property <code>a</code> and some property <code>b</code> to exist within <code>someObject</code> (i.e, <code>someObject</code> could be <code>{ a: 'dataA', b: 'dataB' }</code>, for example) and that we want to place whatever the values are of those keys/properties within <code>const</code> variables of the same name. That&rsquo;s why the syntax above would provide us with two variables <code>const a = someObject.a</code> and <code>const b = someObject.b</code> .</p>
<p>What that means is that there are two sides to Object Destructuring. The &ldquo;Template&rdquo; side and the &ldquo;Source&rdquo; side, where the <code>const { a, b }</code> side (the left-hand side) is the <em>template</em> and the <code>someObject</code> side (the right-hand side) is the <em>source</em> side - which  makes sense - we are defining a structure or &ldquo;template&rdquo; on the left that mirrors the data on &ldquo;source&rdquo; side.</p>
<p>Again, just to make this clear, here are a few examples:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// ----- Destructure from Object Variable with const ----- //
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">objOne</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">a</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataA&#39;</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">b</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataB&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructure
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">objOne</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">a</span>); <span style="color:#75715e">// dataA
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">b</span>); <span style="color:#75715e">// dataB
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// ----- Destructure from Object Variable with let ----- //
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">objTwo</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">c</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataC&#39;</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">d</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataD&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructure
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> { <span style="color:#a6e22e">c</span>, <span style="color:#a6e22e">d</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">objTwo</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">c</span>); <span style="color:#75715e">// dataC
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">d</span>); <span style="color:#75715e">// dataD
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructure from Object Literal with const ----- //
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">e</span>, <span style="color:#a6e22e">f</span> } <span style="color:#f92672">=</span> { <span style="color:#a6e22e">e</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataE&#39;</span>, <span style="color:#a6e22e">f</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataF&#39;</span> }; <span style="color:#75715e">// &lt;-- Destructure
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">e</span>); <span style="color:#75715e">// dataE
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">f</span>); <span style="color:#75715e">// dataF
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructure from Object Literal with let ----- //
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> { <span style="color:#a6e22e">g</span>, <span style="color:#a6e22e">h</span> } <span style="color:#f92672">=</span> { <span style="color:#a6e22e">g</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataG&#39;</span>, <span style="color:#a6e22e">h</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataH&#39;</span> }; <span style="color:#75715e">// &lt;-- Destructure
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">g</span>); <span style="color:#75715e">// dataG
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">h</span>); <span style="color:#75715e">// dataH 
</span></span></span></code></pre></div><p>In the case of nested properties, mirror the same structure in your destructing assignment:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Richard P. Feynman&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Theoretical Physicist&#39;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">location</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">lat</span><span style="color:#f92672">:</span>  <span style="color:#ae81ff">1</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">lng</span><span style="color:#f92672">:</span>  <span style="color:#ae81ff">2</span>
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Attempt one:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">occupation</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">name</span>); <span style="color:#75715e">// Richard P. Feynman
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">occupation</span>); <span style="color:#75715e">// The entire `occupation` object.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Attempt two:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> { <span style="color:#a6e22e">type</span>, <span style="color:#a6e22e">location</span> } } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">type</span>); <span style="color:#75715e">// Theoretical Physicist
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">location</span>) <span style="color:#75715e">// The entire `location` object.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Attempt three:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> {  <span style="color:#a6e22e">location</span><span style="color:#f92672">:</span> { <span style="color:#a6e22e">lat</span>, <span style="color:#a6e22e">lng</span> } } } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">lat</span>); <span style="color:#75715e">// 1
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">lng</span>); <span style="color:#75715e">// 2
</span></span></span></code></pre></div><p>As you can see, the properties you decide to pull off are optional, and to unpack nested properties, simply mirror the structure of the original object (the source) in the template side of your destructuring syntax. If you attempt to destructure a property that does not exist on the original object, that value will be undefined.</p>
<p>We can additionally destructure a variable without first declaring it - assignment without declaration - using the following syntax:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">occupation</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Richard P. Feynman&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">occupation</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Theoretical Physicist&#39;</span> 
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>;({ <span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">occupation</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">name</span>); <span style="color:#75715e">// Richard P. Feynman
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">occupation</span>); <span style="color:#75715e">// Theoretical Physicist
</span></span></span></code></pre></div><p>We precede the expression with a semicolon as to ensure we don&rsquo;t accidentally create an IIFE (Immediately Invoked Function Expression) with a function on a previous line (if one such function exists), and the parentheses around the assignment statement are required as to stop JavaScript from treating your left-hand (template) side as a block.</p>
<p>A very common use case of destructuring exists within function arguments:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">config</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">baseUrl</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;baseURL&gt;&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">awsBucket</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;bucket&gt;&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">secret</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;secret-key&gt;&#39;</span> <span style="color:#75715e">// &lt;- Make this an env var.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructures `baseUrl` and `awsBucket` off `config`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">performOperation</span> <span style="color:#f92672">=</span> ({ <span style="color:#a6e22e">baseUrl</span>, <span style="color:#a6e22e">awsBucket</span> }) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">fetch</span>(<span style="color:#a6e22e">baseUrl</span>).<span style="color:#a6e22e">then</span>(() =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Done&#39;</span>));
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">awsBucket</span>); <span style="color:#75715e">// &lt;bucket&gt;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">performOperation</span>(<span style="color:#a6e22e">config</span>);
</span></span></code></pre></div><p>As you can see, we could have just used the normal destructuring syntax we are now used to inside of the function, like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">config</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">baseUrl</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;baseURL&gt;&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">awsBucket</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;bucket&gt;&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">secret</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;secret-key&gt;&#39;</span> <span style="color:#75715e">// &lt;- Make this an env var.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">performOperation</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">someConfig</span> =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">baseUrl</span>, <span style="color:#a6e22e">awsBucket</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">someConfig</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">fetch</span>(<span style="color:#a6e22e">baseUrl</span>).<span style="color:#a6e22e">then</span>(() =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Done&#39;</span>));
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">awsBucket</span>); <span style="color:#75715e">// &lt;bucket&gt;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">performOperation</span>(<span style="color:#a6e22e">config</span>);
</span></span></code></pre></div><p>But placing said syntax inside the function signature performs destructuring automatically and saves us a line.</p>
<p>A real-world use case of this is in React Functional Components for <code>props</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> <span style="color:#a6e22e">React</span> <span style="color:#a6e22e">from</span> <span style="color:#e6db74">&#39;react&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructure `titleText` and `secondaryText` from `props`.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">default</span> ({ <span style="color:#a6e22e">titleText</span>, <span style="color:#a6e22e">secondaryText</span> }) =&gt; (
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">div</span><span style="color:#f92672">&gt;</span>
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">h1</span><span style="color:#f92672">&gt;</span>{<span style="color:#a6e22e">titleText</span>}<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/h1&gt;</span>
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">h3</span><span style="color:#f92672">&gt;</span>{<span style="color:#a6e22e">secondaryText</span>}<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/h3&gt;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/div&gt;</span>
</span></span><span style="display:flex;"><span>);
</span></span></code></pre></div><p>As opposed to:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> <span style="color:#a6e22e">React</span> <span style="color:#a6e22e">from</span> <span style="color:#e6db74">&#39;react&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">default</span> <span style="color:#a6e22e">props</span> =&gt; (
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">div</span><span style="color:#f92672">&gt;</span>
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">h1</span><span style="color:#f92672">&gt;</span>{<span style="color:#a6e22e">props</span>.<span style="color:#a6e22e">titleText</span>}<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/h1&gt;</span>
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">h3</span><span style="color:#f92672">&gt;</span>{<span style="color:#a6e22e">props</span>.<span style="color:#a6e22e">secondaryText</span>}<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/h3&gt;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/div&gt;</span>
</span></span><span style="display:flex;"><span>);
</span></span></code></pre></div><p>In both cases, we can set default values to the properties as well:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">personOne</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;User One&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;BCrypt Hash&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">personTwo</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;BCrypt Hash&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">createUser</span> <span style="color:#f92672">=</span> ({ <span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Anonymous&#39;</span>, <span style="color:#a6e22e">password</span> }) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">password</span>) <span style="color:#66d9ef">throw</span>  <span style="color:#66d9ef">new</span>  Error(<span style="color:#e6db74">&#39;InvalidArgumentException&#39;</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">name</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">password</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">id</span><span style="color:#f92672">:</span> Math.<span style="color:#a6e22e">random</span>().<span style="color:#a6e22e">toString</span>(<span style="color:#ae81ff">36</span>) <span style="color:#75715e">// &lt;--- Should follow RFC 4122 Spec in real app.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>                .<span style="color:#a6e22e">substring</span>(<span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">15</span>) <span style="color:#f92672">+</span> Math.<span style="color:#a6e22e">random</span>()
</span></span><span style="display:flex;"><span>                .<span style="color:#a6e22e">toString</span>(<span style="color:#ae81ff">36</span>).<span style="color:#a6e22e">substring</span>(<span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">15</span>),
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">name</span>,        <span style="color:#75715e">// &lt;-- We&#39;ll discuss this next.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">password</span> <span style="color:#75715e">// &lt;-- We&#39;ll discuss this next.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    };
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">createUser</span>(<span style="color:#a6e22e">personOne</span>); <span style="color:#75715e">// User One, BCrypt Hash
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">createUser</span>(<span style="color:#a6e22e">personTwo</span>); <span style="color:#75715e">// Anonymous, BCrypt Hash
</span></span></span></code></pre></div><p>As you can see, in the event that <code>name</code> is not present when destructured, we provide it a default value. We can do this with the previous syntax as well:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">c</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Default&#39;</span> } <span style="color:#f92672">=</span> { <span style="color:#a6e22e">a</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataA&#39;</span>, <span style="color:#a6e22e">b</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;dataB&#39;</span> };
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">a</span>); <span style="color:#75715e">// dataA
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">b</span>); <span style="color:#75715e">// dataB
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">c</span>); <span style="color:#75715e">// Default
</span></span></span></code></pre></div><p>Arrays can be destructured as too:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myArr</span> <span style="color:#f92672">=</span> [<span style="color:#ae81ff">4</span>, <span style="color:#ae81ff">3</span>];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructuring happens here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> [<span style="color:#a6e22e">valOne</span>, <span style="color:#a6e22e">valTwo</span>] <span style="color:#f92672">=</span> <span style="color:#a6e22e">myArr</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">valOne</span>); <span style="color:#75715e">// 4
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">valTwo</span>); <span style="color:#75715e">// 3
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// ----- Destructuring without assignment: ----- //
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructuring happens here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>;([<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>] <span style="color:#f92672">=</span> [<span style="color:#ae81ff">10</span>, <span style="color:#ae81ff">2</span>]);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">a</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">b</span>); <span style="color:#75715e">// 12
</span></span></span></code></pre></div><p>A practical reason for array destructuring occurs with React Hooks. (And there are many other reasons, I&rsquo;m just using React as an example).</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">import</span> <span style="color:#a6e22e">React</span>, { <span style="color:#a6e22e">useState</span> } <span style="color:#a6e22e">from</span> <span style="color:#e6db74">&#34;react&#34;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">default</span> () =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">const</span> [<span style="color:#a6e22e">buttonText</span>, <span style="color:#a6e22e">setButtonText</span>] <span style="color:#f92672">=</span> <span style="color:#a6e22e">useState</span>(<span style="color:#e6db74">&#34;Default&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">return</span> (
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">button</span> <span style="color:#a6e22e">onClick</span><span style="color:#f92672">=</span>{() =&gt; <span style="color:#a6e22e">setButtonText</span>(<span style="color:#e6db74">&#34;Toggled&#34;</span>)}<span style="color:#f92672">&gt;</span>
</span></span><span style="display:flex;"><span>      {<span style="color:#a6e22e">buttonText</span>}
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/button&gt;</span>
</span></span><span style="display:flex;"><span>  );
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Notice <code>useState</code> is being destructured off the export, and the array functions/values are being destructured off the <code>useState</code> hook. Again, don&rsquo;t worry if the above doesn&rsquo;t make sense - you&rsquo;d have to understand React - and I&rsquo;m merely using it as an example.</p>
<p>While there is more to ES6 Object Destructuring, I&rsquo;ll cover one more topic here: Destructuring Renaming, which is useful to prevent scope collisions or variable shadows, etc. Suppose we want to destructure a property called <code>name</code> from an object called <code>person</code>, but there is already a variable by the name of <code>name</code> in scope. We can rename on the fly with a colon:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// JS Destructuring Naming Collision Example:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Jamie Corkhill&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Alan Touring&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Rename `name` from `person` to `personName` after destructuring.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">personName</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">name</span>); <span style="color:#75715e">// Jamie Corkhill &lt;-- As expected.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">personName</span>); <span style="color:#75715e">// Alan Touring &lt;-- Variable was renamed.
</span></span></span></code></pre></div><p>Finally, we can set default values with renaming too:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Jamie Corkhill&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">location</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;New York City, United States&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">personName</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Anonymous&#39;</span>, <span style="color:#a6e22e">location</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">person</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">name</span>); <span style="color:#75715e">// Jamie Corkhill
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">personName</span>); <span style="color:#75715e">// Anonymous
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">location</span>); <span style="color:#75715e">// New York City, United States
</span></span></span></code></pre></div><p>As you can see, in this case, <code>name</code> from <code>person</code> (<code>person.name</code>) will be renamed to <code>personName</code> and set to the default value of <code>Anonymous</code> if non-existent.</p>
<p>And of course, the same can be performed in function signatures:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">personOne</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;User One&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;BCrypt Hash&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">personTwo</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;BCrypt Hash&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span>  <span style="color:#a6e22e">createUser</span>  <span style="color:#f92672">=</span> ({  <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">personName</span> <span style="color:#f92672">=</span>  <span style="color:#e6db74">&#39;Anonymous&#39;</span>, <span style="color:#a6e22e">password</span> }) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">password</span>) <span style="color:#66d9ef">throw</span>  <span style="color:#66d9ef">new</span>  Error(<span style="color:#e6db74">&#39;InvalidArgumentException&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">personName</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">password</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">id</span><span style="color:#f92672">:</span> Math.<span style="color:#a6e22e">random</span>().<span style="color:#a6e22e">toString</span>(<span style="color:#ae81ff">36</span>).<span style="color:#a6e22e">substring</span>(<span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">15</span>) <span style="color:#f92672">+</span> Math.<span style="color:#a6e22e">random</span>().<span style="color:#a6e22e">toString</span>(<span style="color:#ae81ff">36</span>).<span style="color:#a6e22e">substring</span>(<span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">15</span>),
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">personName</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">password</span> <span style="color:#75715e">// &lt;-- We&#39;ll discuss this next.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    };
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">createUser</span>(<span style="color:#a6e22e">personOne</span>); <span style="color:#75715e">// User One, BCrypt Hash
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">createUser</span>(<span style="color:#a6e22e">personTwo</span>); <span style="color:#75715e">// Anonymous, BCrypt Hash
</span></span></span></code></pre></div><h3 id="es6-object-shorthand">ES6 Object Shorthand</h3>
<p>Suppose you have the following factory: (we&rsquo;ll cover factories later)</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">createPersonFactory</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">location</span>, <span style="color:#a6e22e">position</span>) =&gt; ({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">name</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">location</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">location</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">position</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">position</span>
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>One might use this factory to create a <code>person</code> object, as follows. Also, note that the factory is implicitly returning an object, evident by the parentheses around the brackets of the Arrow Function.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">createPersonFactory</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>, <span style="color:#e6db74">&#39;Texas&#39;</span>, <span style="color:#e6db74">&#39;Developer&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">person</span>); <span style="color:#75715e">// { ... }
</span></span></span></code></pre></div><p>That&rsquo;s what we already know from the ES5 Object Literal Syntax. Notice, however, in the factory function, that the <em>value of each property is the same name as the property identifier (key) itself.</em> That is - <code>location: location</code> or <code>name: name</code>. It turned out that that was a pretty common occurrence with JS developers.</p>
<p>With the shorthand syntax from ES6, we may achieve the same result by rewriting the factory as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">createPersonFactory</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">location</span>, <span style="color:#a6e22e">position</span>) =&gt; ({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">location</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">position</span>
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">createPersonFactory</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>, <span style="color:#e6db74">&#39;Texas&#39;</span>, <span style="color:#e6db74">&#39;Developer&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">person</span>);
</span></span></code></pre></div><p>Producing the output:</p>
<pre tabindex="0"><code class="language-textile" data-lang="textile">{ name: &#39;Jamie&#39;, location: &#39;Texas&#39;, position: &#39;Developer&#39; }
</code></pre><p>It&rsquo;s important to realize that we can only use this shorthand when the object we wish to create is being dynamically created based on variables, <em>where the variable names are the same as the names of the properties to which we want the variables assigned.</em></p>
<p>This same syntax works with object values:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">createPersonFactory</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">location</span>, <span style="color:#a6e22e">position</span>, <span style="color:#a6e22e">extra</span>) =&gt; ({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">location</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">position</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">extra</span>        <span style="color:#75715e">// &lt;- right here. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">extra</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">interests</span><span style="color:#f92672">:</span> [
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#39;Mathematics&#39;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#39;Quantum Mechanics&#39;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#39;Spacecraft Launch Systems&#39;</span>
</span></span><span style="display:flex;"><span>    ],
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">favoriteLanguages</span><span style="color:#f92672">:</span> [
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#39;JavaScript&#39;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#39;C#&#39;</span>
</span></span><span style="display:flex;"><span>    ]
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">person</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">createPersonFactory</span>(<span style="color:#e6db74">&#39;Jamie&#39;</span>, <span style="color:#e6db74">&#39;Texas&#39;</span>, <span style="color:#e6db74">&#39;Developer&#39;</span>, <span style="color:#a6e22e">extra</span>);
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">person</span>);
</span></span></code></pre></div><p>Producing the output:</p>
<pre tabindex="0"><code class="language-textile" data-lang="textile">{ 
    name: &#39;Jamie&#39;,
    location: &#39;Texas&#39;,
    position: &#39;Developer&#39;,
    extra: { 
        interests: [ 
            &#39;Mathematics&#39;,
            &#39;Quantum Mechanics&#39;,
            &#39;Spacecraft Launch Systems&#39; 
        ],
        favoriteLanguages: [ &#39;JavaScript&#39;, &#39;C#&#39; ]
     } 
}
</code></pre><p>As a final example, this works with object literals as well:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">id</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;314159265358979&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Archimedes of Syracuse&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">location</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Syracuse&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">greatMathematician</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">id</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">location</span>
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><h3 id="es6-spread-operator-">ES6 Spread Operator (&hellip;)</h3>
<p>The Spread Operator permits us to do a variety of things, some of which we&rsquo;ll discuss here.</p>
<p>Firstly, we can spread out properties from one object on to another object:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myObjOne</span> <span style="color:#f92672">=</span> { <span style="color:#a6e22e">a</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;a&#39;</span>, <span style="color:#a6e22e">b</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;b&#39;</span> };
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myObjTwo</span> <span style="color:#f92672">=</span> { ...<span style="color:#a6e22e">myObjOne</span> }<span style="color:#f92672">:</span>
</span></span></code></pre></div><p>This has the effect of placing all properties on <code>myObjOne</code> onto <code>myObjTwo</code>, such that <code>myObjTwo</code> is now <code>{ a: 'a', b: 'b' }</code>. We can use this method to override previous properties. Suppose a user wants to update their account:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">user</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;John Doe&#39;</span>, 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">email</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;john@domain.com&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;hash&gt;&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">bio</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Lorem ipsum&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">updates</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;&lt;new-hash&gt;&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">bio</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Ipsum lorem&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">email</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;j@domain.com&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">updatedUser</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    ...<span style="color:#a6e22e">user</span>,    <span style="color:#75715e">// &lt;- original
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    ...<span style="color:#a6e22e">updates</span>  <span style="color:#75715e">// &lt;- updates
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">updatedUser</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/*
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"> {
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     name: &#39;John Doe&#39;,
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     email: &#39;j@domain.com&#39;,    // Updated
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     password: &#39;&lt;new-hash&gt;&#39;,   // Updated
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">     bio: &#39;Ipsum lorem&#39;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"> }
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"> */</span>
</span></span></code></pre></div><p>The same can be performed with arrays:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">apollo13Astronauts</span> <span style="color:#f92672">=</span> [<span style="color:#e6db74">&#39;Jim&#39;</span>, <span style="color:#e6db74">&#39;Jack&#39;</span>, <span style="color:#e6db74">&#39;Fred&#39;</span>];
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">apollo11Astronauts</span> <span style="color:#f92672">=</span> [<span style="color:#e6db74">&#39;Neil&#39;</span>, <span style="color:#e6db74">&#39;Buz&#39;</span>, <span style="color:#e6db74">&#39;Michael&#39;</span>];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">unionOfAstronauts</span> <span style="color:#f92672">=</span> [...<span style="color:#a6e22e">apollo13Astronauts</span>, ...<span style="color:#a6e22e">apollo11Astronauts</span>];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">unionOfAstronauts</span>);
</span></span><span style="display:flex;"><span><span style="color:#75715e">// [&#39;Jim&#39;, &#39;Jack&#39;, &#39;Fred&#39;, &#39;Neil&#39;, &#39;Buz, &#39;Michael&#39;];
</span></span></span></code></pre></div><p>Notice here that we created a union of both sets (arrays) by spreading the arrays out into a new array.</p>
<p>There is a lot more to the Rest/Spread Operator, but it is out of scope for this article. It can be used to attain multiple arguments to a function, for example. If you want to learn more, view the MDN Documentation <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">here</a>.</p>
<h3 id="es6-asyncawait">ES6 Async/Await</h3>
<p>Async/Await is a syntax to ease the pain of promise chaining.</p>
<p>The <code>await</code> reserved keyword permits you to &ldquo;await&rdquo; the settling of the promise, but it may only be used in functions marked with the <code>async</code> keyword. Suppose I have a function that returns a promise. In a new <code>async</code> function, I can <code>await</code> the result of that promise instead of using <code>.then</code> and <code>.catch</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Returns a promise.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myFunctionThatReturnsAPromise</span> <span style="color:#f92672">=</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> Promise((<span style="color:#a6e22e">resolve</span>, <span style="color:#a6e22e">reject</span>) =&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">setTimeout</span>(() =&gt; <span style="color:#a6e22e">resolve</span>(<span style="color:#e6db74">&#39;Hello&#39;</span>), <span style="color:#ae81ff">3000</span>);
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myAsyncFunction</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">async</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">promiseResolutionResult</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">myFunctionThatReturnsAPromise</span>();
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">promiseResolutionResult</span>);
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Writes the log statement after three seconds.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">myAsyncFunction</span>();
</span></span></code></pre></div><p>There are a few things to note here. When we use <code>await</code> in an <code>async</code> function, only the resolved value goes into the variable on the left-hand side. If the function rejects, that&rsquo;s an error that we have to catch, as we&rsquo;ll see in a moment. Additionally, any function marked <code>async</code> will, by default, return a promise.</p>
<p>Let&rsquo;s suppose I needed to make two API calls, one with the response from the former. Using promises and promise chaining, you might do it this way:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">makeAPICall</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">route</span> =&gt; <span style="color:#66d9ef">new</span>  Promise((<span style="color:#a6e22e">resolve</span>, <span style="color:#a6e22e">reject</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">route</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">resolve</span>(<span style="color:#a6e22e">route</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">main</span> <span style="color:#f92672">=</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/whatever&#39;</span>)
</span></span><span style="display:flex;"><span>        .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">response</span> =&gt; <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#a6e22e">response</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39; second call&#39;</span>))
</span></span><span style="display:flex;"><span>        .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">response</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">response</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39; logged&#39;</span>))
</span></span><span style="display:flex;"><span>        .<span style="color:#66d9ef">catch</span>(<span style="color:#a6e22e">err</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">error</span>(<span style="color:#a6e22e">err</span>))
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">main</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Result:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#75715e">/* 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">/whatever 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">/whatever second call 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">/whatever second call logged
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">*/</span>
</span></span></code></pre></div><p>What&rsquo;s happening here is that we first call <code>makeAPICall</code> passing to it <code>/whatever</code>, which gets logged the first time. The promise resolves with that value. Then we call <code>makeAPICall</code> again, passing to it <code>/whatever second call</code>, which gets logged, and again, the promise resolves with that new value. Finally, we take that new value <code>/whatever second call</code> which the promise just resolved with, and log it ourselves in the final log, appending on <code> logged</code> at the end. If this doesn&rsquo;t make sense, you should look into promise chaining.</p>
<p>Using <code>async</code>/<code>await</code>, we can refactor to the following:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">main</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">async</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">resultOne</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/whatever&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">resultTwo</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#a6e22e">resultOne</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39; second call&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">resultTwo</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39; logged&#39;</span>);
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>Here is what will happen. The entire function will stop executing at the very first <code>await</code> statement until the promise from the first call to <code>makeAPICall</code> resolves, upon resolution, the resolved value will be placed in <code>resultOne</code>. When that happens, the function will move to the second <code>await</code> statement, again pausing right there for the duration of the promise settling. When the promise resolves, the resolution result will be placed in <code>resultTwo</code>. If the idea about function execution sounds blocking, fear not, it&rsquo;s still asynchronous, and I&rsquo;ll discuss why in a minute.</p>
<p>This only depicts the &ldquo;happy&rdquo; path. In the event that one of the promises reject, we can catch that with try/catch, for if the promise rejects, an error will be thrown.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">main</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">async</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">resultOne</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/whatever&#39;</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">resultTwo</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#a6e22e">resultOne</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39; second call&#39;</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">resultTwo</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39; logged&#39;</span>);
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">e</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>As I said earlier, any function declared <code>async</code> will return a promise. So, if you want to call an async function from another function, you can use normal promises, or <code>await</code> if you declare the calling function <code>async</code>. However, if you want to call an <code>async</code> function from top-level code and await its result, then you&rsquo;d have to use <code>.then</code> and <code>.catch</code>.</p>
<p>For example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">returnNumberOne</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">async</span> () =&gt; <span style="color:#ae81ff">1</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">returnNumberOne</span>().<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">value</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">value</span>)); <span style="color:#75715e">// 1
</span></span></span></code></pre></div><p>Or, you could use an Immedieately Invoked Function Expression (IIFE):</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span>(<span style="color:#66d9ef">async</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">value</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">returnNumberOne</span>();
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">value</span>); <span style="color:#75715e">// 1
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>})();
</span></span></code></pre></div><p>When you use <code>await</code> in an <code>async</code> function, the execution of the function will stop at that await statement until the promise settles. However, all other functions are free to proceed with execution, thus no extra CPU resources are allocated nor is the thread ever blocked. I&rsquo;ll say that again - operations in that specific function at that specific time will stop until the promise settles, but all other functions are free to fire. Consider an HTTP Web Server - on a per-request basis, all functions are free to fire for all users concurrently as requests are made, it&rsquo;s just that the async/await syntax will provide the <em>illusion</em> that an operation is <em>synchronous</em> and <em>blocking</em> as to make promises easier to work with, but again, everything will remain nice and async.</p>
<p>This isn&rsquo;t all there is to <code>async</code>/<code>await</code>, but it should help you to grasp the basic principles.</p>
<h3 id="classical-oop-factories">Classical OOP Factories</h3>
<p>We are now going to leave the <strong>JavaScript</strong> world and enter the <strong>Java</strong> world. There can come a time when the creation process of an object (in this case, an instance of a class - again, Java) is fairly complex or when we want to have different objects produced based upon a series of parameters. An example might be a function that creates different error objects. A factory is a common design pattern in Object-Oriented Programming and is basically a function that creates objects. To explore this, let us move away from JavaScript into the world of Java. This will make sense to developers who come from a Classical OOP (i.e, not prototypal), statically typed language background. <em>If you are not one such developer, feel free to skip this section.</em> This is a small deviation, and so if following along here interrupts your flow of JavaScript, then again, please skip this section.</p>
<p>A common creational pattern, the Factory Pattern permits us to create objects without exposing the required business logic to perform said creation.</p>
<p>Suppose we are writing a program that permits us to visualize primitive shapes in n-dimensions. If we provide a cube, for example, we&rsquo;d see a 2D cube (a square), a 3D cube (a cube), and a 4D cube (a Tesseract, or Hypercube). Here is how this might be done, trivially, and barring the actual drawing part, in Java.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#75715e">// Main.java
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Defining an interface for the shape (can be used as a base type)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IShape</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span><span style="color:#f92672">();</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Implementing the interface for 2-dimensions:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">TwoDimensions</span> <span style="color:#66d9ef">implements</span> IShape <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span><span style="color:#f92672">()</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        System<span style="color:#f92672">.</span><span style="color:#a6e22e">out</span><span style="color:#f92672">.</span><span style="color:#a6e22e">println</span><span style="color:#f92672">(</span><span style="color:#e6db74">&#34;Drawing a shape in 2D.&#34;</span><span style="color:#f92672">);</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Implementing the interface for 3-dimensions:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ThreeDimensions</span> <span style="color:#66d9ef">implements</span> IShape <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span><span style="color:#f92672">()</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        System<span style="color:#f92672">.</span><span style="color:#a6e22e">out</span><span style="color:#f92672">.</span><span style="color:#a6e22e">println</span><span style="color:#f92672">(</span><span style="color:#e6db74">&#34;Drawing a shape in 3D.&#34;</span><span style="color:#f92672">);</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Implementing the interface for 4-dimensions:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FourDimensions</span> <span style="color:#66d9ef">implements</span> IShape <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">@Override</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">draw</span><span style="color:#f92672">()</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        System<span style="color:#f92672">.</span><span style="color:#a6e22e">out</span><span style="color:#f92672">.</span><span style="color:#a6e22e">println</span><span style="color:#f92672">(</span><span style="color:#e6db74">&#34;Drawing a shape in 4D.&#34;</span><span style="color:#f92672">);</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Handles object creation
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ShapeFactory</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Factory method (notice return type is the base interface)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> IShape <span style="color:#a6e22e">createShape</span><span style="color:#f92672">(</span><span style="color:#66d9ef">int</span> dimensions<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">switch</span><span style="color:#f92672">(</span>dimensions<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> 2<span style="color:#f92672">:</span>
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> TwoDimensions<span style="color:#f92672">();</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> 3<span style="color:#f92672">:</span>
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> ThreeDimensions<span style="color:#f92672">();</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">case</span> 4<span style="color:#f92672">:</span>
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> FourDimensions<span style="color:#f92672">();</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">default</span><span style="color:#f92672">:</span> 
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> IllegalArgumentException<span style="color:#f92672">(</span><span style="color:#e6db74">&#34;Invalid dimension.&#34;</span><span style="color:#f92672">);</span>
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Main class and entry point.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Main</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span><span style="color:#f92672">(</span>String<span style="color:#f92672">[]</span> args<span style="color:#f92672">)</span> <span style="color:#66d9ef">throws</span> Exception <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        ShapeFactory shapeFactory <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> ShapeFactory<span style="color:#f92672">();</span>
</span></span><span style="display:flex;"><span>        IShape fourDimensions <span style="color:#f92672">=</span> shapeFactory<span style="color:#f92672">.</span><span style="color:#a6e22e">createShape</span><span style="color:#f92672">(</span>4<span style="color:#f92672">);</span>
</span></span><span style="display:flex;"><span>        fourDimensions<span style="color:#f92672">.</span><span style="color:#a6e22e">draw</span><span style="color:#f92672">();</span> <span style="color:#75715e">// Drawing a shape in 4D.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span></code></pre></div><p>As you can see, we define an interface that specifies a method for drawing a shape.  By having the different classes implement the interface, we can guarantee that all shapes can be drawn (for they all must have an overridable <code>draw</code> method as per the interface definition). Considering this shape is drawn differently depending upon the dimensions within which it&rsquo;s viewed, we define helper classes that implement the interface as to perform the GPU intensive work of simulating n-dimensional rendering. <code>ShapeFactory</code> does the work of instantiating the correct class - the <code>createShape</code> method is a factory, and like the definition above, it is a method that returns an object of a class. The return type of <code>createShape</code> is the <code>IShape</code> interface because the <code>IShape</code> interface is the base type of all shapes (because they have a <code>draw</code> method).</p>
<p>This Java example is fairly trivial, but you can easily see how useful it becomes in larger applications where the setup to create an object might not be so simple. An example of this would be a video game. Suppose the user has to survive different enemies. Abstract classes and interfaces might be used to define core functions available to all enemies (and methods that can be overridden), perhaps employing the delegation pattern (favor composition over inheritance as the Gang of Four suggested so you don&rsquo;t get locked into extending a single base class and to make testing/mocking/DI easier). For enemy objects instantiated in different ways, the interface would permit factory object creation while relying on the generic interface type. This would be very relevant if the enemy was created dynamically.</p>
<p>Another example is a builder function. Suppose we utilize the Delegation Pattern to have a class delegate work to other classes that honor an interface. We could place a static <code>build</code> method on the class to have it construct its own instance (assuming you were not using Dependency Injection). Instead of having to call each setter, you can do this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">User</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> IMessagingService msgService<span style="color:#f92672">;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> String name<span style="color:#f92672">;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">int</span> age<span style="color:#f92672">;</span>
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">User</span><span style="color:#f92672">(</span>String name<span style="color:#f92672">,</span> <span style="color:#66d9ef">int</span> age<span style="color:#f92672">,</span> IMessagingService msgService<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> name<span style="color:#f92672">;</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">age</span> <span style="color:#f92672">=</span> age<span style="color:#f92672">;</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">msgService</span> <span style="color:#f92672">=</span> msgService<span style="color:#f92672">;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> User <span style="color:#a6e22e">build</span><span style="color:#f92672">(</span>String name<span style="color:#f92672">,</span> <span style="color:#66d9ef">int</span> age<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> User<span style="color:#f92672">(</span>name<span style="color:#f92672">,</span> age<span style="color:#f92672">,</span> <span style="color:#66d9ef">new</span> SomeMessageService<span style="color:#f92672">());</span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">}</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">}</span>
</span></span></code></pre></div><p>I&rsquo;ll be explaining the Delegation Pattern in a later article if you&rsquo;re not familiar with it - basically, through Composition and in terms of object-modeling, it creates a &ldquo;has-a&rdquo; relationship instead of an &ldquo;is-a&rdquo; relationship as you&rsquo;d get with inheritance. If you have a <code>Mammal</code> class and a <code>Dog</code> class, and <code>Dog</code> extends <code>Mammal</code>, then a <code>Dog</code> <strong>is-a</strong> <code>Mammal</code>. Whereas, if you had a <code>Bark</code> class, and you just passed instances of <code>Bark</code> into the constructor of <code>Dog</code>, then <code>Dog</code> <strong>has-a</strong> <code>Bark</code>. As you might imagine, this especially makes unit testing easier, for you can inject mocks and assert facts about the mock as long as mock honors the interface contract in the testing environment.</p>
<p>The <code>static</code> &ldquo;build&rdquo; factory method above simply creates a new object of <code>User</code> and passes a concrete <code>MessageService</code> in. Notice how this follows from the definition above - not exposing the business logic to create an object of a class, or, in this case, not exposing the creation of the messaging service to the caller of the factory.</p>
<p>Again,  this is not necessarily how you would do things in the real world, but it presents the idea of a factory function/method quite well. We might use a Dependency Injection container instead, for example. Now back to JavaScript.</p>
<h3 id="starting-with-express">Starting with Express</h3>
<p>Express is a Web Application Framework for Node (available via an NPM Module) that permits one to create an HTTP Web Server. It&rsquo;s important to note that Express is not the only framework to do this (there exists Koa, Fastify, etc.), and that, as seen in the previous article, Node can function without Express as a stand-alone entity. (Express is merely a module that was designed for Node - Node can do many things without it, although Express is popular for Web Servers).</p>
<p>Again, let me make a very important distinction. <strong>There is</strong> a dichotomy present between Node/JavaScript and Express. Node, the runtime/environment within which you run JavaScript, can do many things - such as permitting you to build React Native apps, desktop apps, command-line tools, etc. - Express is nothing but a lightweight framework that permits you to use Node/JS to build web servers as opposed to dealing with Node&rsquo;s low-level network and HTTP APIs. You don&rsquo;t need Express to build a web server.</p>
<p>Before starting this section, if you are not familiar with HTTP and HTTP Requests (GET, POST, etc.), then I encourage you to read the corresponding section of my former article, which is linked above.</p>
<p>Using Express, we&rsquo;ll set up different routes to which HTTP Requests may be made, as well as the related endpoints (which are callback functions) that will fire when a request is made to that route. Don&rsquo;t worry if routes and endpoints are currently non-sensical - I&rsquo;ll be explaining them later.</p>
<p>Unlike other articles, I&rsquo;ll take the approach of writing the source code as we go, line-by-line, rather than dumping the entire codebase into one snippet and then explaining later. Let&rsquo;s begin by opening a terminal (I&rsquo;m using Terminus on top of Git Bash on Windows - which is a nice option for Windows users who want a Bash Shell without setting up the Linux Subsystem), setting up our project&rsquo;s boilerplate, and opening it in Visual Studio Code.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>mkdir server <span style="color:#f92672">&amp;&amp;</span> cd server
</span></span><span style="display:flex;"><span>touch server.js
</span></span><span style="display:flex;"><span>npm init -y
</span></span><span style="display:flex;"><span>npm install express
</span></span><span style="display:flex;"><span>code .
</span></span></code></pre></div><p>Inside the <code>server.js</code> file, I&rsquo;ll begin by requiring <code>express</code> using the <code>require()</code> function.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>);
</span></span></code></pre></div><p><code>require('express')</code> tells Node to go out and get the Express module we installed earlier, which is currently inside the <code>node_modules</code> folder (for that&rsquo;s what <code>npm install</code> does - create a <code>node_modules</code> folder and puts modules and their dependencies in there). By convention, and when dealing with Express, we call the variable that holds the return result from <code>require('express')</code> <code>express</code>, although it may be called anything.</p>
<p>This returned result, which we have called <code>express</code>, is actually a function - a function we&rsquo;ll have to invoke to create our Express app and set up our routes. Again, by convention, we call this <code>app</code> - <code>app</code> being the return result of <code>express()</code> - that is, the return result of calling the function that has the name <code>express</code> as <code>express()</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>); 
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Note that the above variable names are the convention, but not required.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// An example such as that below could also be used.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">foo</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">bar</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">foo</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Note also that the node module we installed is called express.
</span></span></span></code></pre></div><p>The line <code>const app = express();</code> simply puts a new Express Application inside of the <code>app</code> variable. It calls a function named <code>express</code> (the return result of <code>require('express')</code>) and stores its return result in a constant named <code>app</code>. If you come from an object-oriented programming background, consider this equivalent to instantiating a new object of a class, where <code>app</code> would be the object and where <code>express()</code> would call the constructor function of the <code>express</code> class. Remember, JavaScript allows us to store functions in variables - functions are first-class citizens. The <code>express</code> variable, then, is nothing more than a mere function. It&rsquo;s provided to us by the developers of Express.</p>
<p>I apologize in advance if I&rsquo;m taking a very long time to discuss what is actually very basic, but the above, although primitive, confused me quite a lot when I was first learning back-end development with Node.</p>
<p>Inside the Express source code, which is open-source on GitHub, the variable we called <code>express</code> is a function entitled <code>createApplication</code>, which, when invoked, performs the work necessary to create an Express Application:</p>
<p>A snippet of Express source code:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">exports</span>  <span style="color:#f92672">=</span>  <span style="color:#a6e22e">module</span>.<span style="color:#a6e22e">exports</span>  <span style="color:#f92672">=</span> <span style="color:#a6e22e">createApplication</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/*
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"> * Create an express application
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"> */</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is the function we are storing in the express variable. (- Jamie)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">createApplication</span>() {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   <span style="color:#75715e">// This is what I mean by &#34;Express App&#34; (- Jamie)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>   <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">handle</span>(<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   };
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">mixin</span>(<span style="color:#a6e22e">app</span>, <span style="color:#a6e22e">EventEmitter</span>.<span style="color:#a6e22e">prototype</span>, <span style="color:#66d9ef">false</span>);
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">mixin</span>(<span style="color:#a6e22e">app</span>, <span style="color:#a6e22e">proto</span>, <span style="color:#66d9ef">false</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   <span style="color:#75715e">// expose the prototype that will get set on requests
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">request</span> <span style="color:#f92672">=</span> Object.<span style="color:#a6e22e">create</span>(<span style="color:#a6e22e">req</span>, {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">app</span><span style="color:#f92672">:</span> { <span style="color:#a6e22e">configurable</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#a6e22e">enumerable</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#a6e22e">writable</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#a6e22e">value</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">app</span>      }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   })
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   <span style="color:#75715e">// expose the prototype that will get set on responses
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">response</span> <span style="color:#f92672">=</span> Object.<span style="color:#a6e22e">create</span>(<span style="color:#a6e22e">res</span>, {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">app</span><span style="color:#f92672">:</span> { <span style="color:#a6e22e">configurable</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#a6e22e">enumerable</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#a6e22e">writable</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#a6e22e">value</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">app</span> }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   })
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">init</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>   <span style="color:#75715e">// See - `app` gets returned. (- Jamie)
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>   <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">app</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>GitHub: <a href="https://github.com/expressjs/express/blob/master/lib/express.js">https://github.com/expressjs/express/blob/master/lib/express.js</a></p>
<p>With that short deviation complete, let&rsquo;s continue setting up Express. Thus far, we have required the module and set up our <code>app</code> variable.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>();
</span></span></code></pre></div><p>From here, we have to tell Express to listen on a port. Any HTTP Requests made to the URL and Port upon which our application is listening will be handled by Express. We do that by calling <code>app.listen(...)</code>, passing to it the port and a callback function which gets called when the server starts running:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port {PORT}.`</span>));
</span></span></code></pre></div><p>We notate the <code>PORT</code> variable in capital by convention, for it is a constant variable that will never change. You could do that with all variables that you declare <code>const</code>, but that would look messy. It&rsquo;s up to the developer or development team to decide on notation, so we&rsquo;ll use the above sparsely. I use <code>const</code> everywhere as a method of &ldquo;defensive coding&rdquo; - that is, if I know that a variable is never going to change then I might as well just declare it <code>const</code>. Since I define everything <code>const</code>, I make the distinction between what variables should remain the same on a per-request basis and what variables are true actual global constants.</p>
<p>Here is what we have thus far:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>); 
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>(); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// We will build our API here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding our application to port 3000.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; {
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Let&rsquo;s test this to see if the server starts running on port 3000.</p>
<p>I&rsquo;ll open a terminal and navigate to our project&rsquo;s root directory. I&rsquo;ll then run <code>node server/server.js</code>. Note that this assumes you have Node already installed on your system (You can check with <code>node -v</code>).</p>
<p>If everything works, you should see the following in the terminal:</p>
<p><code>Server is up on port 3000.</code></p>
<p>Go ahead and hit <code>Ctrl + C</code> to bring the server back down.</p>
<p>If this doesn&rsquo;t work for you, or if you see an error such as <code>EADDRINUSE</code>, then it means you may have a service already running on port 3000. Pick another port number, like 3001, 3002, 5000, 8000, etc. Be aware, lower number ports are reserved and there is an upper bound of 65535.</p>
<p>At this point, it&rsquo;s worth taking another small deviation as to understand servers and ports in the context of computer networking. We&rsquo;ll return to Express in a moment. I take this approach, rather than introducing servers and ports first, for the purpose of relevance. That is, it is difficult to learn a concept if you fail to see its applicability. In this way, you are already aware of the use case for ports and servers with Express, so the learning experience will be more pleasurable.</p>
<h3 id="a-brief-look-at-servers-and-ports">A Brief Look at Servers and Ports</h3>
<p>A server is simply a computer or computer program that provides some sort of &ldquo;functionality&rdquo; to the clients that talk to it. More generally, it&rsquo;s a device, usually connected to the Internet, that handles connections in a pre-defined manner. In our case, that &ldquo;pre-defined manner&rdquo; will be HTTP or the HyperText Transfer Protocol. Servers that use the HTTP Protocol are called Web Servers.</p>
<p>When building an application, the server is a critical component of the &ldquo;client-server model&rdquo;, for it permits the sharing and syncing of data (generally via databases or file systems) across devices. It&rsquo;s a cross-platform approach, in a way, for the SDKs of platforms against which you may want to code - be they web, mobile, or desktop - all provide methods (APIs) to interact with a server over HTTP or TCP/UDP Sockets. It&rsquo;s important to make a distinction here - by APIs, I mean programming language constructs to talk to a server, like <code>XMLHttpRequest</code> or the <code>Fetch</code> API in JavaScript, or <code>HttpUrlConnection</code> in Java, or even <code>HttpClient</code> in C#/.NET. This is different from the kind of REST API we&rsquo;ll be building in this article to perform CRUD Operations on a database.</p>
<p>To talk about ports, it&rsquo;s important to understand how clients connect to a server. A client requires the IP Address of the server and the Port Number of our specific service on that server. An IP Address, or Internet Protocol Address, is just an address that uniquely identifies a device on a network. Public and private IPs exist, with private addresses commonly used behind a router or Network Address Translator on a local network. You might see private IP Addresses of the form <code>192.168.XXX.XXX</code> or <code>10.0.XXX.XXX</code>. When articulating an IP Address, decimals are called &ldquo;dots&rdquo;. So <code>192.168.0.1</code> (a common router IP Addr.) might be pronounced, &ldquo;one nine two dot one six eight dot zero dot one&rdquo;. (By the way, if you&rsquo;re ever in a hotel and your phone/laptop won&rsquo;t direct you to the AP captive portal, try typing 192.168.0.1 or 192.168.1.1 or similar directly into Chrome).</p>
<p>For simplicity, and since this is not an article about the complexities of computer networking, assume that an IP Address is equivalent to a house address, allowing you to uniquely identify a house (where a house is analogous to a server, client, or network device) in a neighborhood. One neighborhood is one network. Put together all of the neighborhoods in the United States, and you have the public Internet. (This is a basic view, and there are many more complexities - firewalls, NATs, ISP Tiers (Tier One, Tier Two, and Tier Three), fiber optics and fiber optic backbones, packet switches, hops, hubs, etc., subnet masks, etc., to name just a few - in the real networking world.) The <code>traceroute</code> Unix command can provide more insight into the above, displaying the path (and associated latency) that packets take through a network as a series of &ldquo;hops&rdquo;.</p>
<p>A Port Number identifies a specific service running on a server. SSH, or Secure Shell, which permits remote shell access to a device, commonly runs on port 22. FTP or File Transfer Protocol (which might, for example, be used with an FTP Client to transfer static assets to a server) commonly runs on Port 21. We might say, then, that ports are specific rooms inside each house in our analogy above, for rooms in houses are made for different things - a bedroom for sleeping, a kitchen for food preparation, a dining room for consumption of said food, etc., just like ports correspond to programs that perform specific services. For us, Web Servers commonly run on Port 80, although you are free to specify whichever Port Number you wish as long they are not in use by some other service (they can&rsquo;t collide).</p>
<p>In order to access a website, you need the IP Address of the site. Despite that, we normally access websites via a URL. Behind the scenes, a DNS, or Domain Name Server, converts that URL into an IP Address, allowing the browser to make a GET Request to the server, <em>get</em> the HTML, and render it to the screen. <code>8.8.8.8</code> is the address of one of Google&rsquo;s Public DNS Servers. You might imagine that requiring the resolution of a hostname to an IP Address via a remote DNS Server will take time, and you&rsquo;d be right. To reduce latency, Operating Systems have a DNS Cache - a temporary database that stores DNS lookup information, thereby reducing the frequency of which said lookups must occur. The DNS Resolver Cache can be viewed on Windows with the <code>ipconfig /displaydns</code> CMD command and purged via the <code>ipconfig /flushdns</code> command.</p>
<p>On a Unix Server, more common lower number ports, like 80, require <em>root</em> level (<em>escalated</em> if you come from a Windows background) privileges. For that reason, we&rsquo;ll be using port 3000 for our development work, but will allow the server to choose the port number (whatever is available) when we deploy to our production environment.</p>
<p>Finally, note that we can type IP Addresses directly in Google Chrome&rsquo;s search bar, thus bypassing the DNS Resolution mechanism. Typing <code>216.58.194.36</code>, for example, will take you to Google.com. In our development environment, when using our own computer as our dev server, we&rsquo;ll be using <code>localhost</code> and port 3000. An address is formatted as <code>hostname:port</code>, so our server will be up on <code>localhost:3000</code>. Localhost, or <code>127.0.0.1</code>, is the loopback address, and means the address of &ldquo;this computer&rdquo;. It is a hostname, and its IPv4 address resolves to <code>127.0.0.1</code>. Try pinging localhost on your machine right now. You might get <code>::1</code> back - which is the IPv6 loopback address, or <code>127.0.0.1</code> back - which is the IPv4 loopback address. IPv4 and IPv6 are two different IP Address formats associated with different standards - some IPv6 addresses can be converted to IPv4 but not all.</p>
<h3 id="returning-to-express">Returning to Express</h3>
<p>I mentioned HTTP Requests, Verbs, and Status Codes in my previous article, <a href="https://www.smashingmagazine.com/2019/02/node-api-http-es6-javascript/">Get Started With Node: An Introduction To APIs, HTTP And ES6+ JavaScript</a>. If you do not have a general understanding of the protocol, feel free to jump to the &ldquo;HTTP and HTTP Requests&rdquo; section of that piece.</p>
<p>In order to get a feel for Express, we are simply going to set up our endpoints for the four fundamental operations we&rsquo;ll be performing on the database - Create, Read, Update, and Delete, known collectively as CRUD.</p>
<p>Remember, we access endpoints by routes in the URL. That is, although the words &ldquo;route&rdquo; and &ldquo;endpoint&rdquo; are commonly used interchangeably, an <em>endpoint</em> is technically a programming language function (like ES6 Arrow Functions) that performs some server-side operation, while a <em>route</em> is what the endpoint is located <em>behind of</em>. We specify these endpoints as callback functions, which Express will fire when the appropriate request is made from the client to the <em>route</em> behind which the endpoint lives. You can remember the above by realizing that it is endpoints that perform a function and the route is the name that is used to access the endpoints. As we&rsquo;ll see, the same route can be associated with multiple endpoints by using different HTTP Verbs (similar to method overloading if you come from a classical OOP background with Polymorphism).</p>
<p>Keep in mind, we are following REST (REpresentational State Transfer) Architecture by permitting clients to make requests to our server. This is, after all, a REST or RESTful API. Specific <strong>requests</strong> made to specific <strong>routes</strong> will fire specific <strong>endpoints</strong> which will do specific <strong>things</strong>. An example of such a &ldquo;thing&rdquo; that an endpoint might do is adding new data to a database, removing data, updating data, etc.</p>
<p>Express knows what endpoint to fire because we tell it, explicitly, the request method (GET, POST, etc.) and the route - we define what functions to fire for specific combinations of the above, and the client makes the request, specifying a route and method. To put this more simply, with Node, we&rsquo;ll tell Express - &ldquo;Hey, if someone makes a GET Request to this route, then go ahead and fire this function (use this endpoint)&rdquo;. Things can get more complicated: &ldquo;Express, if someone makes a GET Request to <em>this</em> route, but they don&rsquo;t send up a valid Authorization Bearer Token in the header of their request, then please respond with an <code>HTTP 401 Unauthorized</code>. If they do possess a valid Bearer Token, then please send down whatever protected resource they were looking for by firing the endpoint. Thanks very much and have a nice day.&rdquo; Indeed, it&rsquo;d be nice if programming languages could be that high level without leaking ambiguity, but it nonetheless demonstrates the basic concepts.</p>
<p>Remember, the endpoint, in a way, <em>lives behind</em> the route. So it&rsquo;s imperative that the client provides, in the header of the request, what method it wants to use so that Express can figure out what to do. The request will be made to a specific route, which the client will specify (along with the request type) when contacting the server, allowing Express to do what it needs to do and us to do what we need to do when Express fires our callbacks. That&rsquo;s what it all comes down to.</p>
<p>In the code examples earlier, we called the <code>listen</code> function which was available on <code>app</code>, passing to it a port and callback. <code>app</code> itself, if you remember, is the return result from calling the <code>express</code> variable as a function (that is, <code>express()</code>), and the <code>express</code> variable is what we named the return result from requiring <code>'express'</code> from our <code>node_modules</code> folder. Just like <code>listen</code> is called on <code>app</code>, we specify HTTP Request Endpoints by calling them on <code>app</code>. Let&rsquo;s look at GET:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/my-test-route&#39;</span>, () =&gt; {
</span></span><span style="display:flex;"><span>   <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>The first parameter is a <code>string</code>, and it is the route behind which the endpoint will live. The callback function is the endpoint. I&rsquo;ll say that again: <em>the callback function - the second parameter - is the endpoint</em> that will fire when an HTTP GET Request is made to whatever route we specify as the first argument (<code>/my-test-route</code> in this case).</p>
<p>Now, before we do any more work with Express, we need to know how routes work. The route we specify as a string will be called by making the request to <code>www.domain.com/the-route-we-chose-earlier-as-a-string</code>. In our case, the domain is <code>localhost:3000</code>, which means, in order to fire the callback function above, we have to make a GET Request to <code>localhost:3000/my-test-route</code>. If we used a different string as the first argument above, the URL would have to be different to match what we specified in JavaScript.</p>
<p>When talking about such things, you&rsquo;ll likely hear of Glob Patterns. We could say that all of our API&rsquo;s routes are located at the <code>localhost:3000/**</code> Glob Pattern, where <code>**</code> is a wildcard meaning any directory or sub-directory (note that routes are <strong>not</strong> directories) to which root is a parent - that is, everything.</p>
<p>Let&rsquo;s go ahead and add a log statement into that callback function so that altogether we have:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Getting the module from node_modules.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Creating our Express Application.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Defining the port we&#39;ll bind to.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Defining a new endpoint behind the &#34;/my-test-route&#34; route.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/my-test-route&#39;</span>, () =&gt; {
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A GET Request was made to /my-test-route.&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding the server to port 3000.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; {
</span></span><span style="display:flex;"><span>   <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>)
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>We&rsquo;ll get our server up and running by executing <code>node server/server.js</code> (with Node installed on our system and accessible globally from system environment variables) in the project&rsquo;s root directory. Like earlier, you should see the message that the server is up in the console. Now that the server is running, open a browser, and visit <code>localhost:3000</code> in the URL bar.</p>
<p>You should be greeted with an error message that states <code>Cannot GET /</code>. Press Ctrl + Shift + I on Windows in Chrome to view the developer console. In there, you should see that we have a <code>404</code> (Resource not found). That makes sense - we have only told the server what to do when someone visits <code>localhost:3000/my-test-route</code>. The browser has nothing to render at <code>localhost:3000</code> (which is equivalent to <code>localhost:3000/</code> with a slash).</p>
<p>If you look at the terminal window where the server is running, there should be no new data. Now, visit <code>localhost:3000/my-test-route</code> in your browser&rsquo;s URL bar. You <em>might</em> see the same error in Chrome&rsquo;s Console (because the browser is caching the content and still has no HTML to render), but if you view your terminal where the server process is running, you&rsquo;ll see that the callback function did indeed fire and the log message was indeed logged.</p>
<p>Shut down the server with Ctrl + C.</p>
<p>Now, let&rsquo;s give the browser something to render when a GET Request is made to that route so we can lose the <code>Cannot GET /</code> message. I&rsquo;m going to take our <code>app.get()</code> from earlier, and in the callback function, I&rsquo;m going to add two arguments. Remember, the callback function we are passing in is getting called by Express behind the scenes, and Express can add whatever arguments it wants. It actually adds two (well, technically three, but we&rsquo;ll see that later), and while they are both extremely important, we don&rsquo;t care about the first one for now. The second argument is called <code>res</code>, short for <code>response</code>, and I&rsquo;ll access it by setting <code>undefined</code> as the first parameter:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/my-test-route&#39;</span>, (<span style="color:#66d9ef">undefined</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A GET Request was made to /my-test-route.&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Again, we can call the <code>res</code> argument whatever we want, but <code>res</code> is convention when dealing with Express. <code>res</code> is actually an object, and upon it exist different methods for sending data back to the client. In this case, I&rsquo;m going to access the <code>send(...)</code> function available on <code>res</code> to send back HTML which the browser will render. We are not limited to sending back HTML, however, and can choose to send back text, a JavaScript Object, a stream (streams are especially beautiful), or whatever.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/my-test-route&#39;</span>, (<span style="color:#66d9ef">undefined</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A GET Request was made to /my-test-route.&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>(<span style="color:#e6db74">&#39;&lt;h1&gt;Hello, World!&lt;/h1&gt;&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>If you shut down the server and then bring it back up, and then refresh your browser at the <code>/my-test-route</code> route, you&rsquo;ll see the HTML get rendered.</p>
<p>The Network Tab of the Chrome Developer Tools will allow you to see this GET Request with more detail as it pertains to headers.</p>
<p>At this point, it&rsquo;ll serve us well to start learning about Express Middleware - functions that can be fired globally after a client makes a request.</p>
<h3 id="express-middleware">Express Middleware</h3>
<p>Express provides methods by which to define custom middleware for your application. Indeed, the meaning of Express Middleware is best defined in the Express Docs, <a href="https://expressjs.com/en/guide/using-middleware.html">here</a>)</p>
<blockquote>
<p><em>Middleware</em> functions are functions that have access to the <a href="https://expressjs.com/en/4x/api.html#req">request object</a> (<code>req</code>), the <a href="https://expressjs.com/en/4x/api.html#res">response object</a> (<code>res</code>), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named <code>next</code>.</p>
<p>Middleware functions can perform the following tasks:</p>
<ul>
<li>Execute any code.</li>
<li>Make changes to the request and the response objects.</li>
<li>End the request-response cycle.</li>
<li>Call the next middleware function in the stack.</li>
</ul>
</blockquote>
<p>In other words, a middleware function is a custom function that we (the developer) can define, and that will act as an intermediary between when Express receives the request and when our appropriate callback function fires. We might make a <code>log</code> function, for example, that will log every time a request is made. Note that we can also choose to make these middleware functions fire <em>after</em> our endpoint has fired, depending upon where you place it in the stack - something we&rsquo;ll see later.</p>
<p>In order to specify custom middleware, we have to define it as a function and pass it into <code>app.use(...)</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myMiddleware</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Middleware has fired at time </span><span style="color:#e6db74">${</span>Date().<span style="color:#a6e22e">now</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">myMiddleware</span>); <span style="color:#75715e">// This is the app variable returned from express().
</span></span></span></code></pre></div><p>All together, we now have:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Getting the module from node_modules.  
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span>  <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>);  
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Creating our Express Application.  
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span>  <span style="color:#a6e22e">express</span>();  
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Our middleware function.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myMiddleware</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Middleware has fired at time </span><span style="color:#e6db74">${</span>Date().<span style="color:#a6e22e">now</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Tell Express to use the middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">myMiddleware</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Defining the port we&#39;ll bind to.  
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span>  <span style="color:#ae81ff">3000</span>;  
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Defining a new endpoint behind the &#34;/my-test-route&#34; route. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/my-test-route&#39;</span>, () =&gt; { 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A GET Request was made to /my-test-route.&#39;</span>);  
</span></span><span style="display:flex;"><span>});  
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding the server to port 3000. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; { 
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>)  
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>If you make the requests through the browser again, you should now see that your middleware function is firing and logging timestamps. To foster experimentation, try removing the call to the <code>next</code> function and see what happens.</p>
<p>The middleware callback function gets called with three arguments, <code>req</code>, <code>res</code>, and <code>next</code>. <code>req</code> is the parameter we skipped over when building out the GET Handler earlier, and it is an object containing information regarding the request, such as headers, custom headers, parameters, and any body that might have been sent up from the client (such as you do with a POST Request). I know we are talking about middleware here, but both the endpoints and the middleware function get called with <code>req</code> and <code>res</code>. <code>req</code> and <code>res</code> will be the same (unless one or the other mutates it) in both the middleware and the endpoint within the scope of a single request from the client. That means, for example, you could use a middleware function to sanitize data by stripping any characters that might be aimed at performing SQL or NoSQL Injections, and then handing the safe <code>req</code> to the endpoint.</p>
<p><code>res</code>, as seen earlier, permits you to send data back to the client in a handful of different ways.</p>
<p><code>next</code> is a callback function that you have to execute when the middleware has finished doing its job in order to call the next middleware function in the stack or the endpoint. Be sure to take note that you will have to call this in the <code>then</code> block of any async functions you fire in the middleware. Depending on your async operation, you may or may not want to call it in the <code>catch</code> block. That is, the <code>myMiddleware</code> function fires <em>after</em> the request is made from the client but <em>before</em> the endpoint function of the request is fired. When we execute this code and make a request, you should see the <code>Middleware has fired...</code> message <em>before</em> the <code>A GET Request was made to...</code> message in the console. If you don&rsquo;t call <code>next()</code>, the latter part will never run - your endpoint function to the request will not fire.</p>
<p>Note also that I could have defined this function anonymously, as such (a convention to which I&rsquo;ll be sticking):</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>((<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Middleware has fired at time </span><span style="color:#e6db74">${</span>Date().<span style="color:#a6e22e">now</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>For anyone new to JavaScript and ES6, if the way in which the above works does not make immediate sense, the below example should help. We are simply defining a callback function (the anonymous function) which takes another callback function (<code>next</code>) as an argument. We call a function that takes a function argument a Higher Order Function. Look at it the below way - it depicts a basic example of how the Express Source Code might work behind the scenes:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Suppose a request has just been made from the client.\n&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is what (it&#39;s not exactly) the code behind app.use() might look like.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">use</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">callback</span> =&gt; { 
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Simple log statement to see where we are.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Inside use() - the &#34;use&#34; function has been called.&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// This depicts the termination of the middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">next</span> <span style="color:#f92672">=</span> () =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Terminating Middleware!\n&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Suppose req and res are defined above (Express provides them).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">req</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">res</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// &#34;callback&#34; is the &#34;middleware&#34; function that is passed into &#34;use&#34;.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// &#34;next&#34; is the above function that pretends to stop the middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">callback</span>(<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>);
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is analogous to the middleware function we defined earlier.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// It gets passed in as &#34;callback&#34; in the &#34;use&#34; function above.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myMiddleware</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Inside the myMiddleware function!&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Here, we are actually calling &#34;use()&#34; to see everything work. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">myMiddleware</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Moving on to actually handle the HTTP Request or the next middleware function.&#39;</span>);
</span></span></code></pre></div><p>We first call <code>use</code> which takes <code>myMiddleware</code> as an argument. <code>myMiddleware</code>, in and of itself, is a function which takes three arguments - <code>req</code>, <code>res</code>, and <code>next</code>. Inside <code>use</code>, <code>myMiddlware</code> is called, and those three arguments are passed in. <code>next</code> is a function defined in <code>use</code>. <code>myMiddleware</code> is defined as <code>callback</code> in the <code>use</code> method. If I&rsquo;d placed <code>use</code>, in this example, on an object called <code>app</code>, we could have mimicked Express&rsquo;s setup entirely, albeit without any sockets or network connectivity.</p>
<p>In this case, both <code>myMiddleware</code> and <code>callback</code> are Higher Order Functions, because they both take functions as arguments.</p>
<p>If you execute this code, you will see the following response:</p>
<pre tabindex="0"><code>Suppose a request has just been made from the client. 

Inside use() - the &#34;use&#34; function has been called. 
Inside the middleware function! 
Terminating Middleware! 

Moving on to actually handle the HTTP Request or the next middleware function.
</code></pre><p>Note that I could have also used anonymous functions to achieve the same result:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Suppose a request has just been made from the client.&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is what (it&#39;s not exactly) the code behind app.use() might look like.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">use</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">callback</span> =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Simple log statement to see where we are.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Inside use() - the &#34;use&#34; function has been called.&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// This depicts the termination of the middlewear.  
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span>  <span style="color:#a6e22e">next</span>  <span style="color:#f92672">=</span>  ()  =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Terminating Middlewear!&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Suppose req and res are defined above (Express provides them).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">req</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">res</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// &#34;callback&#34; is the function which is passed into &#34;use&#34;.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// &#34;next&#34; is the above function that pretends to stop the middlewear.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">callback</span>(<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, () =&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Terminating Middlewear!&#39;</span>);
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Here, we are actually calling &#34;use()&#34; to see everything work.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">use</span>((<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Inside the middlewear function!&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">next</span>();
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Moving on to actually handle the HTTP Request.&#39;</span>);
</span></span></code></pre></div><p>With that hopefully settled, we can now return to the actual task at hand - setting up our middleware.</p>
<p>The fact of the matter is, you will commonly have to send data up through an HTTP Request. You have a few different options for doing so - sending up URL Query Parameters, sending up data that will be accessible on the <code>req</code> object that we learned about earlier, etc. That object is not only available in the callback to calling <code>app.use()</code>, but also to any endpoint. We used <code>undefined</code> as a filler earlier so we could focus on <code>res</code> to send HTML back to the client, but now, we need access to it.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#e6db74">&#39;/my-test-route&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The req object contains client-defined data that is sent up.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// The res object allows the server to send data back down.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>HTTP POST Requests <em>might</em> require that we send a body object up to the server. If you have a form on the client, and you take the user&rsquo;s name and email, you will likely send that data to the server on the body of the request.</p>
<p>Let&rsquo;s take a look at what that might look like on the client side:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-html" data-lang="html"><span style="display:flex;"><span><span style="color:#75715e">&lt;!DOCTYPE html&gt;</span> 
</span></span><span style="display:flex;"><span>&lt;<span style="color:#f92672">html</span>&gt; 
</span></span><span style="display:flex;"><span>    &lt;<span style="color:#f92672">body</span>&gt; 
</span></span><span style="display:flex;"><span>        &lt;<span style="color:#f92672">form</span> <span style="color:#a6e22e">action</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;http://localhost:3000/email-list&#34;</span> <span style="color:#a6e22e">method</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;POST&#34;</span> &gt; 
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">input</span> <span style="color:#a6e22e">type</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;text&#34;</span> <span style="color:#a6e22e">name</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;nameInput&#34;</span>&gt;
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">input</span> <span style="color:#a6e22e">type</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;email&#34;</span> <span style="color:#a6e22e">name</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;emailInput&#34;</span>&gt; 
</span></span><span style="display:flex;"><span>            &lt;<span style="color:#f92672">input</span> <span style="color:#a6e22e">type</span><span style="color:#f92672">=</span><span style="color:#e6db74">&#34;submit&#34;</span>&gt;
</span></span><span style="display:flex;"><span>       &lt;/<span style="color:#f92672">form</span>&gt; 
</span></span><span style="display:flex;"><span>   &lt;/<span style="color:#f92672">body</span>&gt; 
</span></span><span style="display:flex;"><span>&lt;/<span style="color:#f92672">html</span>&gt;
</span></span></code></pre></div><p>On the server side:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/email-list&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// What do we now? 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// How do we access the values for the user&#39;s name and email?
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>To access the user&rsquo;s name and email, we&rsquo;ll have to use a particular type of middleware. This will put the data on an object called <code>body</code> available on <code>req</code>. Body Parser was a popular method of doing this, available by the Express developers as a standalone NPM module. Now, Express comes pre-packaged with its own middleware to do this, and we&rsquo;ll call it as so:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">urlencoded</span>({ <span style="color:#a6e22e">extended</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> }));
</span></span></code></pre></div><p>Now we can do:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/email-list&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;User Name: &#39;</span>, <span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">nameInput</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;User Email: &#39;</span>, <span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">emailInput</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>All this does is take any user-defined input which is sent up from the client, and makes them available on the <code>body</code> object of <code>req</code>. Note that on <code>req.body</code>, we now have <code>nameInput</code> and <code>emailInput</code>, which are the names of the <code>input</code> tags in the HTML. Now, this client-defined data should be considered dangerous (never, never trust the client), and needs to be sanitized, but we&rsquo;ll cover that later.</p>
<p>Another type of middleware provided by express is <code>express.json()</code>. <code>express.json</code> is used to package any JSON Payloads sent up in a request from the client onto <code>req.body</code>, while <code>express.urlencoded</code> will package any incoming requests with strings, arrays, or other URL Encoded data onto <code>req.body</code>. In short, both manipulate <code>req.body</code>, but <code>.json()</code> is for JSON Payloads and <code>.urlencoded()</code> is for, among others, POST Query Parameters.</p>
<p>Another way of saying this is that incoming requests with a <code>Content-Type: application/json</code> header (such as specifying a POST Body with the <code>fetch</code> API) will be handled by <code>express.json()</code>, while requests with header <code>Content-Type: application/x-www-form-urlencoded</code> (such as HTML Forms) will be handled with <code>express.urlencoded()</code>. This hopefully now makes sense.</p>
<h3 id="starting-our-crud-routes-for-mongodb">Starting our CRUD Routes for MongoDB</h3>
<p>Considering that we understand that we specify each endpoint by calling the relevant function on <code>app</code>, passing to it the route and a callback function containing the request and response objects, we can begin to define our CRUD Routes for the Bookshelf API. Indeed, and considering this is an introductory article, I won&rsquo;t be taking care to follow HTTP and REST specifications completely, nor will I attempt to use the cleanest possible architecture. That will come in a future article.</p>
<p>I&rsquo;ll open up the <code>server.js</code> file that we have been using thus far and empty everything out as to start from the below clean slate:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Getting the module from node_modules.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This creates our Express App.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>(); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Define middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">json</span>());
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">urlencoded</span>({ <span style="color:#a6e22e">extended</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> ));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Listening on port 3000 (arbitrary).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Not a TCP or UDP well-known port. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Does not require superuser privileges.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// We will build our API here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding our application to port 3000.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>));
</span></span></code></pre></div><p>Consider all following code to take up the <code>// ...</code> portion of the file above.</p>
<p>To define our endpoints, and because we are building a REST API, we should discuss the proper way to name routes. Again, you should take a look at the HTTP section of my former article for more information. We are dealing with books, so all routes will be located behind <code>/books</code> (the plural naming convention is standard).</p>
<table>
<thead>
<tr>
<th>Request</th>
<th style="text-align:left">Route</th>
</tr>
</thead>
<tbody>
<tr>
<td>POST</td>
<td style="text-align:left"><code>/books</code></td>
</tr>
<tr>
<td>GET</td>
<td style="text-align:left"><code>/books/id</code></td>
</tr>
<tr>
<td>PATCH</td>
<td style="text-align:left"><code>/books/id</code></td>
</tr>
<tr>
<td>DELETE</td>
<td style="text-align:left"><code>/books/id</code></td>
</tr>
</tbody>
</table>
<p>As you can see, an ID does not need to be specified when POSTing a book because we&rsquo;ll (or rather, MongoDB), will be generating it for us, automatically, server-side. GETting, PATCHing, and DELETing books will all require that we do pass that ID to our endpoint, which we&rsquo;ll discuss later. For now, let&rsquo;s simply create the endpoints:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// HTTP POST /books
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A POST Request was made!&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP GET /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A GET Request was made! Getting book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP PATCH /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">patch</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A PATCH Request was made! Updating book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP DELETE /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#66d9ef">delete</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A DELETE Request was made! Deleting book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>The <code>:id</code> syntax tells Express that <code>id</code> is a dynamic parameter that will be passed up in the URL. We have access to it on the <code>params</code> object which is available on <code>req</code>. I know &ldquo;we have access to it on <code>req</code>&rdquo; sounds like magic and magic (which doesn&rsquo;t exist) is dangerous in programming, but you have to remember that Express is not a black box. It&rsquo;s an open-source project available on GitHub under an MIT LIcense. You can easily view it&rsquo;s source code if you want to see how dynamic query parameters are put onto the <code>req</code> object.</p>
<p>All together, we now have the following in our <code>server.js</code> file:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Getting the module from node_modules.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This creates our Express App.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>(); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Define middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">json</span>());
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">urlencoded</span>({ <span style="color:#a6e22e">extended</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> }));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Listening on port 3000 (arbitrary).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Not a TCP or UDP well-known port. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Does not require superuser privileges.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// We will build our API here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP POST /books
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A POST Request was made!&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP GET /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A GET Request was made! Getting book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP PATCH /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">patch</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A PATCH Request was made! Updating book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP DELETE /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#66d9ef">delete</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A DELETE Request was made! Deleting book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding our application to port 3000.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>));
</span></span></code></pre></div><p>Go ahead and start the server, running <code>node server.js</code> from the terminal or command line, and visit your browser. Open the Chrome Development Console, and in the URL (Uniform Resource Locator) Bar, visit <code>localhost:3000/books</code>. You should already see the indicator in your OS&rsquo;s terminal that the server is up as well as the log statement for GET.</p>
<p>Thus far, we&rsquo;ve been using a web browser to perform GET Requests. That is good for just starting out, but we&rsquo;ll quickly find that better tools exist to test API routes. Indeed, we could paste <code>fetch</code> calls directly into the console or use some online service. In our case, and to save time, we&rsquo;ll use <code>cURL</code> and Postman. I use both in this article (although you could use either or) so that I can introduce them for if you haven&rsquo;t used them. <code>cURL</code> is a library (a very, very important library) and command-line tool designed to transfer data using various protocols. Postman is a GUI based tool for testing APIs. After following the relevant installation instructions for both tools on your operating system, ensure your server is still running, and then execute the following commands (one-by-one) in a new terminal. It&rsquo;s important that you type them and execute them individually, and then watch the log message in the separate terminal from your server. Also, note that the standard programming language comment symbol <code>//</code> is not a valid symbol in Bash or MS-DOS. You&rsquo;ll have to omit those lines, and I only use them here to describe each block of <code>cURL</code> commands.</p>
<pre tabindex="0"><code>// HTTP POST Request (Localhost, IPv4, IPv6)
curl -X POST http://localhost:3000/books
curl -X POST http://127.0.0.1:3000/books
curl -X POST http://[::1]:3000/books

// HTTP GET Request (Localhost, IPv4, IPv6)
curl -X GET http://localhost:3000/books/123abc
curl -X GET http://127.0.0.1:3000/books/book-id-123
curl -X GET http://[::1]:3000/books/book-abc123

// HTTP PATCH Request (Localhost, IPv4, IPv6)
curl -X PATCH http://localhost:3000/books/456
curl -X PATCH http://127.0.0.1:3000/books/218
curl -X PATCH http://[::1]:3000/books/some-id

// HTTP DELETE Request (Localhost, IPv4, IPv6)
curl -X DELETE http://localhost:3000/books/abc
curl -X DELETE http://127.0.0.1:3000/books/314
curl -X DELETE http://[::1]:3000/books/217
</code></pre><p>As you can see, the ID that is passed in as a URL Parameter can be any value. The <code>-X</code> flag specifies the type of HTTP Request (it can be omitted for GET), and we provide the URL to which the request will be made thereafter. I&rsquo;ve duplicated each request three times, allowing you to see that everything still works whether you use the <code>localhost</code> hostname, the IPv4 Address (<code>127.0.0.1</code>) to which <code>localhost</code> resolves, or the IPv6 Address (<code>::1</code>) to which <code>localhost</code> resolves. Note that <code>cURL</code> requires wrapping IPv6 Addresses in square brackets.</p>
<p>We are in a decent place now - we have the simple structure of our routes and endpoints set up. The server runs correctly and accepts HTTP Requests as we expect it to. Contrary to what you might expect, there is not long to go at this point - we just have to set up our database, host it (using a Database-as-a-Service - MongoDB Atlas), and persist data to it (and perform validation and create error responses).</p>
<h3 id="setting-up-a-production-mongodb-database">Setting up a Production MongoDB Database</h3>
<p>To set up a production database, we&rsquo;ll head over to the <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas Home Page</a> and sign up for a free account. Thereafter, create a new cluster. You can maintain the default settings, picking a fee tier applicable region. Then hit the &ldquo;Create Cluster&rdquo; button. The cluster will take some time to create, and then you&rsquo;ll be able to attain your database URL and password. Take note of these when you see them. We&rsquo;ll hardcode them for now, and then store them in environment variables later for security purposes. For help in creating and connecting to a cluster, I&rsquo;ll refer you to the MongoDB Documentation, particularly <a href="https://docs.atlas.mongodb.com/create-new-cluster/">this page</a> and <a href="https://docs.atlas.mongodb.com/connect-to-cluster/">this page</a>, or you can leave a comment below and I&rsquo;ll try to help.</p>
<h3 id="creating-a-mongoose-model">Creating a Mongoose Model</h3>
<p>It&rsquo;s recommended that you have an understanding of the meanings of Documents and Collections in the context of NoSQL (Not Only SQL - Structured Query Language). For reference, you might want to read both the <a href="https://mongoosejs.com/docs/index.html">Mongoose Quick Start Guide</a> and the <a href="https://www.smashingmagazine.com/2019/02/node-api-http-es6-javascript/">MongoDB</a> section of my former article.</p>
<p>We now have a database that is ready to accept CRUD Operations. Mongoose is a Node module (or ODM - Object Document Mapper) that will allow us to perform those operations (abstracting away some of the complexities) as well as set up the schema, or structure, of the database collection.</p>
<p>As an important disclaimer, there is a lot of controversy around ORMs and such patterns as Active Record or Data Mapper. Some developers swear by ORMs and others swear against them (believing they get in the way). It&rsquo;s also important to note that ORMs abstract a lot away like connection pooling, socket connections, and handling, etc. You could easily use the MongoDB Native Driver (another NPM Module), but it would talk a lot more work. While it&rsquo;s recommended that you play with the Native Driver before using ORMs, I omit the Native Driver here for brevity. For complex SQL operations on a Relational Database, not all ORMs will be optimized for query speed, and you may end up writing your own raw SQL. ORMs can come into play a lot with Domain-Driven Design and CQRS, among others. They are an established concept in the .NET world, and the Node.js community has not completely caught up yet - TypeORM is better, but it&rsquo;s not NHibernate or Entity Framework.</p>
<p>To create our Model, I&rsquo;ll create a new folder in the <code>server</code> directory entitled <code>models</code>, within which I&rsquo;ll create a single file with the name <code>book.js</code>. Thus far, our project&rsquo;s directory structure is as follows:</p>
<pre tabindex="0"><code>- server
  - node_modules
  - models
    - book.js
  - package.json
  - server.js
</code></pre><p>Indeed, this directory structure is not required, but I use it here because it&rsquo;s simple. Allow me to note that this is not at all the kind of architecture you want to use for larger applications (and you might not even want to use JavaScript - TypeScript could be a better option), which I discuss in this article&rsquo;s closing. The next step will be to install <code>mongoose</code>, which is performed via, as you might expect, <code>npm i mongoose</code>.</p>
<p>The meaning of a Model is best ascertained from the Mongoose documentation:</p>
<blockquote>
<p><a href="https://mongoosejs.com/docs/api.html#model-js">Models</a> are fancy constructors compiled from <code>Schema</code> definitions. An instance of a model is called a <a href="https://mongoosejs.com/docs/documents.html">document</a>. Models are responsible for creating and reading documents from the underlying MongoDB database.</p>
</blockquote>
<p>Before creating the Model, we&rsquo;ll define its Schema. A Schema will, among others, make certain expectations about the value of the properties provided. MongoDB is schemaless, and thus this functionality is provided by the Mongoose ODM. Let&rsquo;s start with a simple example. Suppose I want my database to store a user&rsquo;s name, email address, and password. Traditionally, as a plain old JavaScript Object (POJO), such a structure might look like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">userDocument</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Jamie Corkhill&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">email</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;jamie@domain.com&#39;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Bcrypt Hash&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>If that above object was how we expected our user&rsquo;s object to look, then we would need to define a schema for it, like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">schema</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">email</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">password</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>Notice that when creating our schema, we define what properties will be available on each document in the collection as an object in the schema. In our case, that&rsquo;s <code>name</code>, <code>email</code>, and <code>password</code>. The fields <code>type</code>, <code>trim</code>, <code>required</code> tell Mongoose what data to expect. If we try to set the <code>name</code> field to a number, for example, or if we don&rsquo;t provide a field, Mongoose will throw an error (because we are expecting a type of <code>String</code>), and we can send back a <code>400 Bad Request</code> to the client. This might not make sense right now because we have defined an arbitrary <code>schema</code> object. However, the fields of <code>type</code>, <code>trim</code>, and <code>required</code> (among others) are special validators that Mongoose understands. <code>trim</code>, for example, will remove any whitespace from the beginning and end of the string. We&rsquo;ll pass the above schema to <code>mongoose.Schema()</code> in the future and that function will know what to do with the validators.</p>
<p>Understanding how Schemas work, we&rsquo;ll create the model for our Books Collection of the Bookshelf API. Let&rsquo;s define what data we require:</p>
<ol>
<li>
<p>Title</p>
</li>
<li>
<p>ISBN Number</p>
</li>
<li>
<p>Author</p>
<ol>
<li>
<p>First Name</p>
</li>
<li>
<p>Last Name</p>
</li>
</ol>
</li>
<li>
<p>Publishing Date</p>
</li>
<li>
<p>Finished Reading (Boolean)</p>
</li>
</ol>
<p>I&rsquo;m going to create this in the <code>book.js</code> file we created earlier in <code>/models</code>. Like the example above, we&rsquo;ll be performing validation:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Define the schema:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mySchema</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">title</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">isbn</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">author</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">firstName</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>        },
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">lastName</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">publishingDate</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">finishedReading</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> Boolean,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">default</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><code>default</code> will set a default value for the property if none is provided - <code>finishedReading</code> for example, although a required field, will be set automatically to <code>false</code> if the client does not send one up.</p>
<p>Mongoose also provides the ability to perform custom validation on our fields, which is done by supplying the <code>validate()</code> method, which attains the value that was attempted to be set as its one and only parameter. In this function, we can throw an error if the validation fails. Here is an example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">isbn</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">validate</span>(<span style="color:#a6e22e">value</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">validator</span>.<span style="color:#a6e22e">isISBN</span>(<span style="color:#a6e22e">value</span>)) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> Error(<span style="color:#e6db74">&#39;ISBN is invalid.&#39;</span>);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#75715e">// ...
</span></span></span></code></pre></div><p>Now, if anyone supplies an invalid ISBN to our model, Mongoose will throw an error when trying to save that document to the collection. I&rsquo;ve already installed the NPM module <code>validator</code> via <code>npm i validator</code> and required it. <code>validator</code> contains a bunch of helper functions for common validation requirements, and I use it here instead of RegEx because ISBNs can&rsquo;t be validated with RegEx alone due to a tailing checksum. Remember, users will be sending a JSON body to one of our POST routes. That endpoint will catch any errors (such as an invalid ISBN) when attempting to save, and if one is thrown, it&rsquo;ll return a blank response with an <code>HTTP 400 Bad Request</code> status - we haven&rsquo;t yet added that functionality.</p>
<p>Finally, we have to define our schema of earlier as the schema for our model, so I&rsquo;ll make a call to <code>mongoose.Schema()</code> passing in that schema:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">bookSchema</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">Schema</span>(<span style="color:#a6e22e">mySchema</span>);
</span></span></code></pre></div><p>To make things more precise and clean, I&rsquo;ll replace the <code>mySchema</code> variable with the actual object all on one line:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">bookSchema</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">Schema</span>({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">title</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">isbn</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">validate</span>(<span style="color:#a6e22e">value</span>) {
</span></span><span style="display:flex;"><span>           <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">validator</span>.<span style="color:#a6e22e">isISBN</span>(<span style="color:#a6e22e">value</span>)) {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> Error(<span style="color:#e6db74">&#39;ISBN is invalid.&#39;</span>);
</span></span><span style="display:flex;"><span>           }
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">author</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">firstName</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>        },
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">lastName</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">publishingDate</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">finishedReading</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> Boolean,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">default</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Let&rsquo;s take a final moment to discuss this schema. We are saying that each of our documents will consist of a title, an ISBN, an author with a first and last name, a publishing date, and a finishedReading boolean.</p>
<ol>
<li><code>title</code> will be of type <code>String</code>, it&rsquo;s a required field, and we&rsquo;ll trim any whitespace.</li>
<li><code>isbn</code> will be of type <code>String</code>, it&rsquo;s a required field, it must match the validator, and we&rsquo;ll trim any whitespace.</li>
<li><code>author</code> is of type <code>object</code> containing a required, trimmed, <code>string</code> firstName and a required, trimmed, <code>string</code> lastName.</li>
<li><code>publishingDate</code> is of type String (although we could make it of type <code>Date</code> or <code>Number</code> for a Unix timestamp.</li>
<li><code>finishedReading</code> is a required <code>boolean</code> that will default to <code>false</code> if not provided.</li>
</ol>
<p>With our <code>bookSchema</code> defined, Mongoose knows what data and what fields to expect within each document to the collection that stores books. However, how do we tell it what collection that specific schema defines? We could have hundreds of collections, so how do we correlate, or tie, <code>bookSchema</code> to the <code>Book</code> collection?</p>
<p>The answer, as seen earlier, is with the use of models. We&rsquo;ll use <code>bookSchema</code> to create a model, and that model will model the data to be stored in the Book collection, which will be created by Mongoose automatically.</p>
<p>Append the following lines to the end of the file:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Book</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">model</span>(<span style="color:#e6db74">&#39;Book&#39;</span>, <span style="color:#a6e22e">bookSchema</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">module</span>.<span style="color:#a6e22e">exports</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">Book</span>;
</span></span></code></pre></div><p>As you can see, we have created a model, the name of which is <code>Book</code> (- the first parameter to <code>mongoose.model()</code>), and also provided the ruleset, or schema, to which all data is saved in the Book collection will have to abide. We export this model as a default export, allowing us to <code>require</code> the file for our endpoints to access. <code>Book</code> is the object upon which we&rsquo;ll call all of the required functions to Create, Read, Update, and Delete data which are provided by Mongoose.</p>
<p>Altogether, our <code>book.js</code> file should look as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">validator</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;validator&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Define the schema.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">bookSchema</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">Schema</span>({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">title</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">isbn</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">validate</span>(<span style="color:#a6e22e">value</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">validator</span>.<span style="color:#a6e22e">isISBN</span>(<span style="color:#a6e22e">value</span>)) {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> Error(<span style="color:#e6db74">&#39;ISBN is invalid.&#39;</span>);
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">author</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">firstName</span><span style="color:#f92672">:</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>        },
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">lastName</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>            <span style="color:#a6e22e">trim</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">publishingDate</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> String
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">finishedReading</span><span style="color:#f92672">:</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">type</span><span style="color:#f92672">:</span> Boolean,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">required</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">default</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Create the &#34;Book&#34; model of name Book with schema bookSchema.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Book</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">model</span>(<span style="color:#e6db74">&#39;Book&#39;</span>, <span style="color:#a6e22e">bookSchema</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Provide the model as a default export.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">module</span>.<span style="color:#a6e22e">exports</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">Book</span>;
</span></span></code></pre></div><h3 id="connecting-to-mongodb-basics">Connecting to MongoDB (Basics)</h3>
<p>Don&rsquo;t worry about copying down this code. I&rsquo;ll provide a better version in the next section. To connect to our database, we&rsquo;ll have to provide the database URL and password. We&rsquo;ll call the <code>connect</code> method available on <code>mongoose</code> to do so, passing to it the required data. For now, we are going hardcode the URL and password - an extremely frowned upon technique for many reasons: namely the accidental committing of sensitive data to a public (or private made public) GitHub Repository. Realize also that commit history is saved, and that if you accidentally commit a piece of sensitive data, removing it in a future commit will not prevent people from seeing it (or bots from harvesting it), because it&rsquo;s still available in the commit history. CLI tools exist to mitigate this issue and remove history.</p>
<p>As stated, for now, we&rsquo;ll hard code the URL and password, and then save them to environment variables later. At this point, let&rsquo;s look at simply how to do this, and then I&rsquo;ll mention a way to optimize it.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">MONGODB_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your MongoDB URL&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">connect</span>(<span style="color:#a6e22e">MONGODB_URL</span>, {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useNewUrlParser</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useCreateIndex</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useFindAndModify</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useUnifiedTopology</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>This will connect to the database. We provide the URL that we attained from the MongoDB Atlas dashboard, and the object passed in as the second parameter specifies features to use as to, among others, prevent deprecation warnings.</p>
<p>Mongoose, which uses the core MongoDB Native Driver behind the scenes, has to attempt to keep up with breaking changes made to the driver. In a new version of the driver, the mechanism used to parse connection URLs was changed, so we pass the <code>useNewUrlParser: true</code> flag to specify that we want to use the latest version available from the official driver.</p>
<p>By default, if you set indexes (and they are called &ldquo;indexes&rdquo; not &ldquo;indices&rdquo;) (which we won&rsquo;t cover in this article) on data in your database, Mongoose uses the <code>ensureIndex()</code> function available from the Native Driver. MongoDB deprecated that function in favor of <code>createIndex()</code>, and so setting the flag <code>useCreateIndex</code> to true will tell Mongoose to use the <code>createIndex()</code> method from the driver, which is the non-deprecated function.</p>
<p>Mongoose&rsquo;s original version of <code>findOneAndUpdate</code> (which is a method to find a document in a database and update it) pre-dates the Native Driver version. That is, <code>findOneAndUpdate()</code> was not originally a Native Driver function but rather one provided by Mongoose, so Mongoose had to use <code>findAndModify</code> provided behind the scenes by the driver to create <code>findOneAndUpdate</code> functionality. With the driver now updated, it contains its own such function, so we don&rsquo;t have to use <code>findAndModify</code>. This might not make sense, and that&rsquo;s okay - it&rsquo;s not an important piece of information on the scale of things.</p>
<p>Finally, MongoDB deprecated its old server and engine monitoring system. We use the new method with <code>useUnifiedTopology: true</code>.</p>
<p>What we have thus far is a way to connect to the database. But here&rsquo;s the thing - it&rsquo;s not scalable or efficient. When we write unit tests for this API, the unit tests are going to use their own test data (or fixtures) on their own test databases. So, we want a way to be able to create connections for different purposes - some for testing environments (that we can spin up and tear down at will), others for development environments, and others for production environments. To do that, we&rsquo;ll build a factory. (Remember that from earlier?)</p>
<h3 id="connecting-to-mongo---building-an-implementation-of-a-js-factory">Connecting to Mongo - Building an Implementation of a JS Factory</h3>
<p>Indeed, Java Objects are not analogous at all to JavaScript Objects, and so, subsequently, what we know above from the Factory Design Pattern won&rsquo;t apply. I merely provided that as an example to show the traditional pattern. To attain an object in Java, or C#, or C++, etc., we have to instantiate a class. This is done with the <code>new</code> keyword, which instructs the compiler to allocate memory for the object on the heap. In C++, this gives us a pointer to the object that we have to clean up ourselves so we don&rsquo;t have hanging pointers or memory leaks (C++ has no garbage collector, unlike Node/V8 which is built on C++) In JavaScript, the above need not be done - we don&rsquo;t need to instantiate a class to attain an object - an object is just <code>{}</code>. Some people will say that everything in JavaScript is an object, although that is technically not true because primitive types are not objects.</p>
<p>For the above reasons, our JS Factory will be simpler, sticking to the loose definition of a factory being a function that returns an object (a JS object). Since a function is an object (for <code>function</code> inherits from <code>object</code> via prototypal inheritance), our below example will meet this criterion. To implement the factory, I&rsquo;ll create a new folder inside of <code>server</code> called <code>db</code>. Within <code>db</code> I&rsquo;ll create a new file called <code>mongoose.js</code>. This file will make connections to the database. Inside of <code>mongoose.js</code>, I&rsquo;ll create a function called <code>connectionFactory</code> and export it by default:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Directory - server/db/mongoose.js
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">MONGODB_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your MongoDB URL&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">connectionFactory</span> <span style="color:#f92672">=</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">connect</span>(<span style="color:#a6e22e">MONGODB_URL</span>, {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">useNewUrlParser</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">useCreateIndex</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">useFindAndModify</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">module</span>.<span style="color:#a6e22e">exports</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">connectionFactory</span>;
</span></span></code></pre></div><p>Using the shorthand provided by ES6 for Arrow Functions that return one statement on the same line as the method signature, I&rsquo;ll make this file simpler by getting rid of the <code>connectionFactory</code> definition and just exporting the factory by default:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// server/db/mongoose.js
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">MONGODB_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your MongoDB URL&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">module</span>.<span style="color:#a6e22e">exports</span> <span style="color:#f92672">=</span> () =&gt; <span style="color:#a6e22e">mongoose</span>.<span style="color:#a6e22e">connect</span>(<span style="color:#a6e22e">MONGODB_URL</span>, {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useNewUrlParser</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useCreateIndex</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">useFindAndModify</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Now, all one has to do is require the file and call the method that gets exported, like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">connectionFactory</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;./db/mongoose&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">connectionFactory</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// OR
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;./db/mongoose&#39;</span>)();
</span></span></code></pre></div><p>You could invert control by having your MongoDB URL be provided as a parameter to the factory function, but we are going to dynamically change the URL as an environment variable based on environment.</p>
<p>The benefits of making our connection as a function are that we can call that function later in code to connect to the database from files aimed at production and those aimed at local and remote integration testing both on-device and with a remote CI/CD pipeline/build server.</p>
<h3 id="building-our-endpoints">Building our Endpoints</h3>
<p>We now begin to add very simple CRUD related logic to our endpoints. As previously stated, a short disclaimer is in order. The methods by which we go about implementing our business logic here are <strong>not</strong> ones that you should mirror for anything other than simple projects. Connecting to databases and performing logic directly within endpoints is (and should be) frowned upon, for you lose the ability to swap out services or DBMSs without having to perform an application wide refactor. Nonetheless, considering this is a beginner&rsquo;s article, I employ these bad practices here. A future article in this series will discuss how we can increase both the complexity and the quality of our architecture.</p>
<p>For now, let&rsquo;s go back to our <code>server.js</code> file and ensure we both have the same starting point. Notice I added the <code>require</code> statement for our database connection factory and I imported the model we exported from <code>./models/book.js</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Database connection and model.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;./db/mongoose.js&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Book</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;./models/book.js&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This creates our Express App.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>(); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Define middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">json</span>());
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">urlencoded</span>({ <span style="color:#a6e22e">extended</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> }));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Listening on port 3000 (arbitrary).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Not a TCP or UDP well-known port. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Does not require superuser privileges.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// We will build our API here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP POST /books
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;A POST Request was made!&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP GET /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A GET Request was made! Getting book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP PATCH /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">patch</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A PATCH Request was made! Updating book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP DELETE /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#66d9ef">delete</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`A DELETE Request was made! Deleting book </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding our application to port 3000.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>));
</span></span></code></pre></div><p>I&rsquo;m going to start with <code>app.post()</code>. We have access to the <code>Book</code> model because we exported it from the file within which we created it. As stated in the Mongoose docs, <code>Book</code> is constructable. To create a new book, we call the constructor and pass the book data in, as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Book</span>(<span style="color:#a6e22e">bookData</span>);
</span></span></code></pre></div><p>In our case, we&rsquo;ll have <code>bookData</code> as the object sent up in the request, which will be available on <code>req.body.book</code>. Remember, <code>express.json()</code> middleware will put any JSON data that we send up onto <code>req.body</code>. We are to send up JSON in the following format:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;book&#34;</span>: {
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&#34;title&#34;</span>: <span style="color:#e6db74">&#34;The Art of Computer Programming&#34;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&#34;isbn&#34;</span>: <span style="color:#e6db74">&#34;ISBN-13: 978-0-201-89683-1&#34;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&#34;author&#34;</span>: { 
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">&#34;firstName&#34;</span>: <span style="color:#e6db74">&#34;Donald&#34;</span>, 
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">&#34;lastName&#34;</span>: <span style="color:#e6db74">&#34;Knuth&#34;</span> 
</span></span><span style="display:flex;"><span>        }, 
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&#34;publishingDate&#34;</span>: <span style="color:#e6db74">&#34;July 17, 1997&#34;</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">&#34;finishedReading&#34;</span>: <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>What that means, then, is that the JSON we pass up will get parsed, and the entire JSON object (the first pair of braces) will be placed on <code>req.body</code> by the <code>express.json()</code> middleware. The one and only property on our JSON object is <code>book</code>, and thus the <code>book</code> object will be available on <code>req.body.book</code>.</p>
<p>At this point, we can call the model constructor function and pass in our data:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {    <span style="color:#75715e">// &lt;- Notice &#39;async&#39;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Book</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">book</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">book</span>.<span style="color:#a6e22e">save</span>();                      <span style="color:#75715e">// &lt;- Notice &#39;await&#39;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>Notice a few things here. Calling the <code>save</code> method on the instance we get back from calling the constructor function will persist the <code>req.body.book</code> object to the database if and only if it complies with the schema we defined in the Mongoose model. The act of saving data to a database is an asynchronous operation, and this <code>save()</code> method returns a promise  - the settling of which we much await. Rather than chain on a <code>.then()</code> call, I  use the ES6 Async/Await syntax, which means I must make the callback function to <code>app.post</code> <code>async</code>.</p>
<p><code>book.save()</code> will reject with a <code>ValidationError</code> if the object the client sent up does not comply with the schema we defined. Our current setup makes for some very flaky and badly written code, for we don&rsquo;t want our application to crash in the event of a failure regarding validation. To fix that, I&rsquo;ll surround the dangerous operation in a <code>try/catch</code> clause. In the event of an error, I&rsquo;ll return an HTTP 400 Bad Request or an HTTP 422 Unprocessable Entity. There is some amount of debate over which to use, so I&rsquo;ll stick with a 400 for this article since it is more generic.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; { 
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Book</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">book</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">book</span>.<span style="color:#a6e22e">save</span>();    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">201</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;ValidationError&#39;</span> });
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Notice that I use the ES6 Object Shorthand to just return the <code>book</code> object right back to the client in the success case with <code>res.send({ book })</code> - that would be equivalent to <code>res.send({ book: book })</code>. I also return the expression just to make sure my function exits. In the <code>catch</code> block, I set the status to be 400 explicitly, and return the string &lsquo;ValidationError&rsquo; on the <code>error</code> property of the object that gets sent back. A 201 is the success path status code meaning &ldquo;CREATED&rdquo;.</p>
<p>Indeed, this isn&rsquo;t the best solution either because we can&rsquo;t really be sure the reason for failure was a Bad Request on the client&rsquo;s side. Maybe we lost connection (supposed a dropped socket connection, thus a transient exception) to the database, in which case we should probably return a 500 Internal Server error. A way to check this would be to read the <code>e</code> error object and selectively return a response.  Let&rsquo;s do that now, but as I&rsquo;ve said multiple times, a followup article will discuss proper architecture in terms of Routers, Controllers, Services, Repositories, custom error classes, custom error middleware, custom error responses,  Database Model/Domain Entity data mapping, and Command Query Separation (CQS).</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span>  <span style="color:#66d9ef">new</span>  <span style="color:#a6e22e">Book</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">book</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">book</span>.<span style="color:#a6e22e">save</span>();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">ValidationError</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;ValidationError&#39;</span> });
</span></span><span style="display:flex;"><span>        } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">500</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Internal Error&#39;</span> });
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Go ahead and open Postman (assuming you have it, otherwise, download and install it) and create a new request. We&rsquo;ll be making a POST Request to <code>localhost:3000/books</code>. Under the &ldquo;Body&rdquo; tab within the Postman Request section, I&rsquo;ll select the &ldquo;raw&rdquo; radio button and select &ldquo;JSON&rdquo; in the dropdown button to the far right. This will go ahead and automatically add the <code>Content-Type: application/json</code> header to the request. I&rsquo;ll then copy and paste the Book JSON Object from earlier into the Body text area. This is what we have:</p>
<p><img src="/get-started-with-express/POST-Request-With-JSON-One.png" alt="POST Request with JSON"></p>
<p>Thereafter, I&rsquo;ll hit the send button, and you should see a 201 Created response in the &ldquo;Response&rdquo; section of Postman (the bottom row). We see this because we specifically asked Express to respond with a 201 and the Book object - had we just done <code>res.send()</code> with no status code, <code>express</code>  would have automatically responded with a 200 OK. As you can see, the Book object is now saved to the database and has been returned to the client as the Response to the POST Request.</p>
<p><img src="/get-started-with-express/POSTMAN-With-JSON.png" alt="POST Response"></p>
<p>If you view the database Book collection through MongoDB Atlas, you&rsquo;ll see that the book was indeed saved</p>
<p>You can also tell that MongoDB has inserted the <code>__v</code> and <code>_id</code> fields. The former represents the version of the document, in this case, 0, and the latter is the document&rsquo;s ObjectID - which is automatically generated by MongoDB and is guaranteed to have a low collision probability.</p>
<h3 id="a-summary-of-what-we-have-covered-thus-far">A Summary of What We Have Covered Thus Far</h3>
<p>We have covered a lot thus far in the article. Let&rsquo;s take a short reprieve by going over a brief summary before returning to finish the Express API.</p>
<p>We learned about ES6 Object Destructuring, the ES6 Object Shorthand Syntax, as well as the ES6 Rest/Spread operator. All three of those let us do the following (and more, as discussed above):</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// Destructuring Object Properties:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">a</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">newNameA</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Default&#39;</span>, <span style="color:#a6e22e">b</span> } <span style="color:#f92672">=</span> { <span style="color:#a6e22e">a</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;someData&#39;</span>, <span style="color:#a6e22e">b</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;info&#39;</span> };
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`newNameA: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">newNameA</span><span style="color:#e6db74">}</span><span style="color:#e6db74">, b: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">b</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>); <span style="color:#75715e">// newNameA: someData, b: info
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Destructuring Array Elements
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> [<span style="color:#a6e22e">elemOne</span>, <span style="color:#a6e22e">elemTwo</span>] <span style="color:#f92672">=</span> [() =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;hi&#39;</span>), <span style="color:#e6db74">&#39;data&#39;</span>];
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`elemOne(): </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">elemOne</span>()<span style="color:#e6db74">}</span><span style="color:#e6db74">, elemTwo: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">elemTwo</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>); <span style="color:#75715e">// elemOne(): hi, elemTwo: data
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Object Shorthand
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">makeObj</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">name</span>) =&gt; ({ <span style="color:#a6e22e">name</span> });
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`makeObj(&#39;Tim&#39;): </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">JSON</span>.<span style="color:#a6e22e">stringify</span>(<span style="color:#a6e22e">makeObj</span>(<span style="color:#e6db74">&#39;Tim&#39;</span>))<span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>); <span style="color:#75715e">// makeObj(&#39;Tim&#39;): { &#34;name&#34;: &#34;Tim&#34; }
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Rest, Spread
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> [<span style="color:#a6e22e">c</span>, <span style="color:#a6e22e">d</span>, ...<span style="color:#a6e22e">rest</span>] <span style="color:#f92672">=</span> [<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">3</span>, <span style="color:#ae81ff">4</span>];
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`c: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">c</span><span style="color:#e6db74">}</span><span style="color:#e6db74">, d: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">d</span><span style="color:#e6db74">}</span><span style="color:#e6db74">, rest: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">rest</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>) <span style="color:#75715e">// c: 0, d: 1, rest: 2, 3, 4
</span></span></span></code></pre></div><p>We also covered Express, Expess Middleware, Servers, Ports, IP Addressing, etc. Things got interesting when we learned that there exist methods availabile on the return result from <code>require('express')();</code> with the names of the HTTP Verbs, such as <code>app.get</code> and <code>app.post</code>.</p>
<blockquote>
<p>If that <code>require('express')()</code> part didn&rsquo;t make sense to you, this was the point I was making:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">someHTTPVerb</span>
</span></span></code></pre></div><p>It should make sense in the same way that we fired off the connection factory before for Mongoose.</p>
</blockquote>
<p>Each route handler, which is the endpoint function (or callback function), gets passed in a <code>req</code> object and a <code>res</code> object from Express behind the scenes. (They technically also get <code>next</code>, as we&rsquo;ll see in a minute).  <code>req</code> contains data specific to the incoming request from the client, such as headers or any JSON sent up. <code>res</code> is what permits us to return responses to the client. The <code>next</code> function is also passed into handlers.</p>
<p>With Mongoose, we saw how we can connect to the database with two methods - a primitive way and a more advanced/practical way that borrows from the Factory Pattern. We&rsquo;ll end up using this when we discuss Unit and Integration Testing with Jest (and mutation testing) because it&rsquo;ll permit us to spin up a test instance of the DB populated with seed data against which we can run assertions.</p>
<p>After that, we created a Mongoose schema object and used it to create a model, and then learned how we can call the constructor of that model to create a new instance of it. Available on the instance is a <code>save</code> method (among others), which is asynchronous in nature, and which will check that the object structure we passed in complies with the schema, resolving the promise if it does, and rejecting the promise with a <code>ValidationError</code> if it does not. In the event of a resolution, the new document is saved to the database and we respond with an HTTP 200 OK/201 CREATED, otherwise, we catch the thrown error in our endpoint, and return an HTTP 400 Bad Request to the client.</p>
<p>As we continue you building out our endpoints, you&rsquo;ll learn more about some of the methods available on the model and the model instance.</p>
<h3 id="finishing-our-endpoints">Finishing our Endpoints</h3>
<p>Having completed the POST Endpoint, let&rsquo;s handle GET. As I mentioned earlier, the <code>:id</code> syntax inside the route lets Express know that <code>id</code> is a route parameter, accessible from <code>req.params</code>. You already saw that when you match some ID for the param &ldquo;wildcard&rdquo; in the route, it was printed to the screen in the early examples. For instance, if you made a GET Request to &ldquo;/books/test-id-123&rdquo;, then <code>req.params.id</code> would be the string <code>test-id-123</code> because the param name was <code>id</code> by having the route as <code>HTTP GET /books/:id</code>.</p>
<p>So, all we need to do is retrieve that ID from the <code>req</code> object and check to see if any document in our database has the same ID - something made very easy by Mongoose (and the Native Driver).</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">book</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>You can see that accessible upon our model is a function we can call that will find a document by its ID. Behind the scenes, Mongoose will cast whatever ID we pass into <code>findById</code> to the type of the <code>_id</code> field on the document, or in this case, an <code>ObjectId</code>. If a matching ID is found (and only one will ever be found for <code>ObjectId</code> has an extremely low collision probability), that document will be placed in our <code>book</code> constant variable. If not, <code>book</code> will be null - a fact we&rsquo;ll use in the near future.</p>
<p>For now, let&rsquo;s restart the server (you must restart the server unless you&rsquo;re using <code>nodemon</code>) and ensure that we still have the one book document from before inside the <code>Books</code> Collection. Go ahead and copy the ID of that document, the highlighted portion of the image below:</p>
<p><img src="/get-started-with-express/ID-to-use.png" alt="ID to use"></p>
<p>And use it to make a GET Request to <code>/books/:id</code> with Postman as follows (note that the body data is just left over from my earlier POST Request. It’s not actually being used despite the fact that it’s depicted in the image below):</p>
<p><img src="/get-started-with-express/Book-GET-Req.png" alt="Book GET Request"></p>
<p>Upon doing so, you should get the book document with the specified ID back inside the Postman response section. Notice that earlier, with the POST Route, which is designed to &ldquo;POST&rdquo; or &ldquo;push&rdquo; new resources to the server, we responded with a 201 Created - because a new resource (or document) was created. In the case of GET, nothing new was created - we just requested a resource with a specific ID, thus a 200 OK status code is what we got back, instead of 201 Created.</p>
<p>As is common in the field of software development, edge cases must be accounted for - user input is inherently unsafe and erroneous, and it&rsquo;s our job, as developers, to be flexible to the types of input we can be given and to respond to them accordingly. What do we do if the user (or the API Caller) passes us some ID that can&rsquo;t be cast to a MongoDB ObjectID, or an ID that can be cast but that doesn&rsquo;t exist?</p>
<p>For the former case, Mongoose is going to throw a <code>CastError</code> - which is understandable because if we provide an ID like <code>math-is-fun</code>, then that&rsquo;s obviously not something that can be cast to an ObjectID, and casting to an ObjectID is specifically what Mongoose is doing under the hood.</p>
<p>For the latter case, we could easily rectify the issue via a Null Check or a Guard Clause. Either way, I&rsquo;m going to send back and HTTP 404 Not Found Response. I&rsquo;ll show you a few ways we can do this, a bad way and then a better way.</p>
<p>Firstly, we could do the following:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">book</span>) <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> Error();
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>This works and we can use it just fine. I expect that the statement <code>await Book.findById()</code> will throw a Mongoose <code>CastError</code> if the ID string can&rsquo;t be cast to an ObjectID, causing the <code>catch</code> block to execute. If it can be cast but the corresponding ObjectID does not exist, then <code>book</code> will be <code>null</code> and the Null Check will throw an error, again firing the <code>catch</code> block. Inside <code>catch</code>, we just return a 404. There are two problems here. First, even if the Book is found but some other unknown error occurs, we send back a 404 when we should probably give the client a generic catch-all 500. Second, we are not really differentiating between whether the ID sent up is valid but non-existent, or whether it&rsquo;s just a bad ID.</p>
<p>So, here is another way:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">book</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">CastError</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not a valid ID&#39;</span> });
</span></span><span style="display:flex;"><span>        } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">500</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Internal Error&#39;</span> });
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>The nice thing about this is that we can handle all three cases of a 400, a 404 and a generic 500. Notice that after the Null Check on <code>book</code>, I use the <code>return</code> keyword on my response. This is very important because we want to make sure we exit the route handler there.</p>
<p>Some other options might be for us to check if the <code>id</code> on <code>req.params</code> can be cast to an ObjectID explicitly as opposed to permitting Mongoose to cast implicitly with <code> mongoose.Types.ObjectId.isValid('id);</code>, but there is an edge case with 12-byte strings that causes this to sometimes work unexpectedly.</p>
<p>We could make said repetition less painful with <code>Boom</code>, an HTTP Response library, for example, or we could employ Error Handling Middleware. We could also transform Mongoose Errors into something more readable with Mongoose Hooks/Middleware as described <a href="https://mongoosejs.com/docs/middleware.html#error-handling-middleware">here</a>. An additional option would be to define custom error objects and use global Express Error Handling Middleware, however, I&rsquo;ll save that for an upcoming article wherein we discuss better architectural methods.</p>
<p>In the endpoint for <code>PATCH /books/:id</code>, we&rsquo;ll expect an update object to be passed up containing updates for the book in question. For this article, we&rsquo;ll allow all fields to be updated, but in the future, I&rsquo;ll show how we can disallow updates of particular fields. Additionally, you&rsquo;ll see that the error handling logic in our PATCH Endpoint will be the same as our GET Endpoint. That&rsquo;s an indication that we are violating DRY Principles, but again, we&rsquo;ll touch on that later.</p>
<p>I&rsquo;m going to expect that all updates are available on the <code>updates</code> object of <code>req.body</code> (meaning the client will send up JSON containing an <code>updates</code> object) and will use the <code>Book.findByAndUpdate</code> function with a special flag to perform the update.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">patch</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">id</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">updates</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>;
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">updatedBook</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findByIdAndUpdate</span>(<span style="color:#a6e22e">id</span>, <span style="color:#a6e22e">updates</span>, { <span style="color:#a6e22e">runValidators</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#66d9ef">new</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">updatedBook</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">updatedBook</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">CastError</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not a valid ID&#39;</span> });
</span></span><span style="display:flex;"><span>        } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">500</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Internal Error&#39;</span> });
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Notice a few things here. We first destructure <code>id</code> from <code>req.params</code> and <code>updates</code> from <code>req.body</code>.</p>
<p>Available on the <code>Book</code> model is a function by the name of <code>findByIdAndUpdate</code> that takes the ID of the document in question, the updates to perform, and an optional options object. Normally, Mongoose won&rsquo;t re-perform validation for update operations, so the <code>runValidators: true</code> flag we pass in as the <code>options</code> object forces it to do so.  Furthermore, as of Mongoose 4, <code>Model.findByIdAndUpdate</code> no longer returns the modified document but returns the original document instead. The <code>new: true</code> flag (which is false by default) overrides that behavior.</p>
<p>Finally, we can build out our DELETE endpoint, which is quite similar to all of the others:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#66d9ef">delete</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">deletedBook</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findByIdAndDelete</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">deletedBook</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">deletedBook</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">e</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">CastError</span>) {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not a valid ID&#39;</span> });
</span></span><span style="display:flex;"><span>        } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">500</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Internal Error&#39;</span> });
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>With that, our primitive API is complete and you can test it by making HTTP Requests to all endpoints.</p>
<h3 id="a-short-disclaimer-about-architecture-and-how-well-rectify-it">A Short Disclaimer about Architecture and How We&rsquo;ll Rectify It</h3>
<p>From an architectural standpoint, the code we have here is quite bad, it&rsquo;s messy, it&rsquo;s not DRY, it&rsquo;s not SOLID, in fact, you might even call it abhorrent. These so-called &ldquo;Route Handlers&rdquo; are doing a lot more than just &ldquo;handing routes&rdquo; - they are directly interfacing with our database. That means there is absolutely no abstraction.</p>
<p>Let&rsquo;s face it, most applications will never be this small or you could probably get away with serverless architectures with the Firebase Database. Maybe, as we&rsquo;ll see later, users want the ability to upload avatars, quotes, and snippets from their books, etc. Maybe we want to add a live chat feature between users with WebSockets, and let&rsquo;s even go as far as saying we&rsquo;ll open up our application to let users borrow books with one another for a small charge - at which point we need to consider Payment Integration with the Stripe API and shipping logistics with the Shippo API.</p>
<p>Suppose we proceed with our current architecture and add all of this functionality. These route handers, also known as Controller Actions, are going to end up being very, very large with a high <strong>cyclomatic complexity</strong>.  Such a coding style might suit us fine in the early days, but what if we decide that our data is referential and thus PostgreSQL is a better database choice than MongoDB? We now have to refactor our entire application, stripping out Mongoose, altering our Controllers, etc., all of which could lead to potential bugs in the rest of the business logic. Another such example would be that of deciding that AWS S3 is too expensive and we wish to migrate to GCP. Again, this requires an application-wide refactor.</p>
<p>Although there are many opinions around architecture, from Domain-Driven Design, Command Query Responsibility Segregation, and Event Sourcing, to Test-Driven Development, SOILD, Layered Architecture, Onion Architecture, and more, we&rsquo;ll focus on implementing simple Layered Architecture in future articles, consisting of Controllers, Services, and Repositories, and employing Design Patterns like Composition, Adapters/Wrappers, and Inversion of Control via Dependency Injection. While, to an extent, this could be somewhat performed with JavaScript, we&rsquo;ll look into TypeScript options to achieve this architecture as well, permitting us to employ functional programming paradigms such as Either Monads in addition to OOP concepts like Generics.</p>
<p>For now, there are two small changes we can make. Because our error handling logic is quite similar in the <code>catch</code> block of all endpoints, we can extract it to a custom Express Error Handling Middleware function at the very end of the stack.</p>
<h3 id="cleaning-up-our-architecture">Cleaning Up our Architecture</h3>
<p>At present, we are repeating a very large amount of error handling logic across all our endpoints. Instead, we can build an Express Error Handling Middleware function, which is an Express Middleware Function that gets called with an error, the req and res objects, and the next function.</p>
<p>For now, let&rsquo;s build that middleware function. All I&rsquo;m going to do is repeat the same error handling logic we are used to:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>((<span style="color:#a6e22e">err</span>, <span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">err</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">ValidationError</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Validation Error&#39;</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">err</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">CastError</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Not a valid ID&#39;</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">err</span>); <span style="color:#75715e">// Unexpected, so worth logging.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">500</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Internal error&#39;</span> });
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>This doesn&rsquo;t appear to work with Mongoose Errors, but in general, rather than using <code>if/else if/else</code> to determine error instances, you can switch over the error&rsquo;s constructor. I&rsquo;ll leave what we have, however.</p>
<p>In a <strong>synchronous</strong> endpoint/route handler, if you throw an error, Express will catch it and process it with no extra work required on your part. Unfortunately, that&rsquo;s not the case for us. We are dealing with <strong>asynchronous</strong> code. In order to delegate error handling to Express with async route handlers, we much catch the error ourselves and pass it to <code>next()</code>.</p>
<p>So, I&rsquo;ll just permit <code>next</code> to be the third argument into the endpoint, and I&rsquo;ll remove the error handling logic in the <code>catch</code> blocks in favor of just passing the error instance to <code>next</code>, as such:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span>  <span style="color:#66d9ef">new</span>  <span style="color:#a6e22e">Book</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">book</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">book</span>.<span style="color:#a6e22e">save</span>();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">next</span>(<span style="color:#a6e22e">e</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>If you do this to all route handlers, you should end up with the following code:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">express</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;express&#39;</span>); 
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">mongoose</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;mongoose&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Database connection and model.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;./db/mongoose.js&#39;</span>)();
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Book</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;./models/book.js&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This creates our Express App.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">app</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">express</span>(); 
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Define middleware.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">json</span>());
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>(<span style="color:#a6e22e">express</span>.<span style="color:#a6e22e">urlencoded</span>({ <span style="color:#a6e22e">extended</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> }));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Listening on port 3000 (arbitrary).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Not a TCP or UDP well-known port. 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Does not require superuser privileges.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3000</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// We will build our API here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP POST /books
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">post</span>(<span style="color:#e6db74">&#39;/books&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Book</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">book</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">book</span>.<span style="color:#a6e22e">save</span>();    
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">201</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">next</span>(<span style="color:#a6e22e">e</span>)
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP GET /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">get</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">book</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findById</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">book</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>           <span style="color:#a6e22e">next</span>(<span style="color:#a6e22e">e</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP PATCH /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">patch</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">id</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">updates</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">body</span>;
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">updatedBook</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findByIdAndUpdate</span>(<span style="color:#a6e22e">id</span>, <span style="color:#a6e22e">updates</span>, { <span style="color:#a6e22e">runValidators</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>, <span style="color:#66d9ef">new</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">updatedBook</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">updatedBook</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">next</span>(<span style="color:#a6e22e">e</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// HTTP DELETE /books/:id
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#66d9ef">delete</span>(<span style="color:#e6db74">&#39;/books/:id&#39;</span>, <span style="color:#66d9ef">async</span> (<span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">deletedBook</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span>  <span style="color:#a6e22e">Book</span>.<span style="color:#a6e22e">findByIdAndDelete</span>(<span style="color:#a6e22e">req</span>.<span style="color:#a6e22e">params</span>.<span style="color:#a6e22e">id</span>);
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#a6e22e">deletedBook</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">404</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Not Found&#39;</span> });
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">send</span>({ <span style="color:#a6e22e">book</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">deletedBook</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">e</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">next</span>(<span style="color:#a6e22e">e</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Notice - bottom of stack.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">use</span>((<span style="color:#a6e22e">err</span>, <span style="color:#a6e22e">req</span>, <span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">next</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">err</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">ValidationError</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Validation Error&#39;</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">err</span> <span style="color:#66d9ef">instanceof</span> <span style="color:#a6e22e">mongoose</span>.Error.<span style="color:#a6e22e">CastError</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">400</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Not a valid ID&#39;</span> });
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">err</span>); <span style="color:#75715e">// Unexpected, so worth logging.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">status</span>(<span style="color:#ae81ff">500</span>).<span style="color:#a6e22e">send</span>({  <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span>  <span style="color:#e6db74">&#39;Internal error&#39;</span> });
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Binding our application to port 3000.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">listen</span>(<span style="color:#a6e22e">PORT</span>, () =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Server is up on port </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">PORT</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>));
</span></span></code></pre></div><p>Moving further, it would be worth separating our error handling middleware into another file, but that&rsquo;s trivial, and we&rsquo;ll see it in future articles in this series. Additionally, we could use an NPM module named <code>express-async-errors</code> as to permit us to not have to call next in the catch block, but again, I&rsquo;m trying to show you how things are done officially.</p>
<h3 id="a-word-about-cors-and-the-same-origin-policy">A Word About CORS and the Same Origin Policy</h3>
<p>Suppose your website is served from the domain <code>myWebsite.com</code> but your server is at <code>myOtherDomain.com/api</code>. CORS stands for Cross-Origin Resource Sharing and is a mechanism by which cross-domain requests can be performed. In the case above, since the server and front-end JS code are at different domains, you&rsquo;d be making a request across two different origins, which is commonly restricted by the browser for security reasons, and mitigated by supplying specific HTTP headers.</p>
<p>The Same Origin Policy is what performs those aforementioned restrictions - a web browser will only permit requires to be made across the same origin.</p>
<p>We&rsquo;ll touch on CORS and SOP later when we build a Webpack bundled front-end for our Book API with React.</p>
<h3 id="conclusion-and-whats-next">Conclusion and What&rsquo;s Next</h3>
<p>We have discussed a lot in this article. Perhaps it wasn&rsquo;t all fully practical, but it hopefully got you more comfortable working with Express and ES6 JavaScript features. If you are new to programming and Node is the first path down which you are embarking, hopefully the references to statically types languages like Java, C++, and C# helped to highlight some of the differences between JavaScript and its static counterparts.</p>
<p>Next time, we&rsquo;ll finish building out our Book API by making some fixes to our current setup with regards to the Book Routes, as well as adding in User Authentication so that users can own books. We&rsquo;ll do all of this with a similar architecture to what I described here and with MongoDB for data persistence. Finally, we&rsquo;ll permit users to upload avatar images to AWS S3 via Buffers.</p>
<p>In the article thereafter, we&rsquo;ll be rebuilding our application from the ground up in TypeScript, still with Express. We&rsquo;ll also move to PostgreSQL with Knex instead of MongoDB with Mongoose as to depict better architectural practices. Finally, we&rsquo;ll update our avatar image uploading process to use Node Streams (we&rsquo;ll discuss Writable, Readable, Duplex, and Transform Streams). Along the way, we&rsquo;ll cover a great amount of design and architectural patterns and functional paradigms, including</p>
<ul>
<li>Controllers/Controller Actions</li>
<li>Services</li>
<li>Repositories</li>
<li>Data Mapping</li>
<li>The Adapter Pattern</li>
<li>The Factory Pattern</li>
<li>The Delegation Pattern</li>
<li>OOP Principles and Composition vs Inheritance</li>
<li>Inversion of Control via Dependency Injection</li>
<li>SOLID Principles</li>
<li>Coding against interfaces</li>
<li>Data Transfer Objects</li>
<li>Domain Models and Domain Entities</li>
<li>Either Monads</li>
<li>Validation</li>
<li>Decorators</li>
<li>Logging and Logging Levels</li>
<li>Unit Tests, Integration Tests (E2E), and Mutation Tests</li>
<li>The Structured Query Language</li>
<li>Relations</li>
<li>HTTP/Express Security Best Practices</li>
<li>Node Best Practices</li>
<li>OWASP Security Best Practices</li>
<li>And more.</li>
</ul>
<p>Using that new architecture, in the article after that, we&rsquo;ll write Unit, Integration, and Mutation tests, aiming for close to 100 percent testing coverage, and we&rsquo;ll finally discuss setting up a remote CI/CD pipeline with CircleCI, as well as Message Busses, Job/Task Scheduling, and load balancing/reverse proxying.</p>
<p>Hopefully, this article has been helpful, and if you have any queries or concerns, let me know in the comments below.</p>
]]></content>
        </item>
        
        <item>
            <title>Get Started With Node: An Introduction To APIs, HTTP And ES6&#43; JavaScript</title>
            <link>/2019/02/get-started-with-node-an-introduction-to-apis-http-and-es6-javascript/</link>
            <pubDate>Wed, 20 Feb 2019 14:14:52 -0500</pubDate>
            
            <guid>/2019/02/get-started-with-node-an-introduction-to-apis-http-and-es6-javascript/</guid>
            <description>This article was first written for Smashing Magazine on February 20, 2019. You can find it here.
You’ve probably heard of Node.js as being an “asynchronous JavaScript runtime built on Chrome’s V8 JavaScript engine”, and that it “uses an event-driven, non-blocking I/O model that makes it lightweight and efficient”. But for some, that is not the greatest of explanations.
What is Node in the first place? What exactly does it mean for Node to be “asynchronous”, and how does that differ from “synchronous”?</description>
            <content type="html"><![CDATA[<blockquote>
<p>This article was first written for Smashing Magazine on February 20, 2019. You can find it <a href="https://www.smashingmagazine.com/2019/02/node-api-http-es6-javascript/">here</a>.</p>
</blockquote>
<p>You’ve probably heard of Node.js as being an “asynchronous JavaScript runtime built on Chrome’s V8 JavaScript engine”, and that it “uses an event-driven, non-blocking I/O model that makes it lightweight and efficient”. But for some, that is not the greatest of explanations.</p>
<p>What is Node in the first place? What exactly does it mean for Node to be “asynchronous”, and how does that differ from “synchronous”? What is the meaning “event-driven” and “non-blocking” anyway, and how does Node fit into the bigger picture of applications, Internet networks, and servers?</p>
<p>We’ll attempt to answer all of these questions and more throughout this series as we take an in-depth look at the inner workings of Node, learn about the HyperText Transfer Protocol, APIs, and JSON, and build our very own Bookshelf API utilizing MongoDB, Express, Lodash, Mocha, and Handlebars.</p>
<h3 id="what-is-nodejs">What is Node.js</h3>
<p>Node is only an environment, or runtime, within which to run normal JavaScript (with minor differences) outside of the browser. We can use it to build desktop applications (with frameworks like Electron), write web or app servers, and more.</p>
<h3 id="blockingnon-blocking-and-synchronousasynchronous">Blocking/Non-Blocking and Synchronous/Asynchronous</h3>
<p>Suppose we are making a database call to retrieve properties about a user. That call is going to take time, and if the request is &ldquo;blocking&rdquo;, then that means it will block the execution of our program until the call is complete. In this case, we made a “synchronous” request since it ended up blocking the thread.</p>
<p>So, a <em>synchronous</em> operation <em>blocks</em> a process or thread until that operation is complete, leaving the thread in a &ldquo;wait state&rdquo;. An <em>asynchronous</em> operation, on the other hand, is <em>non-blocking</em>. It permits execution of the thread to proceed regardless of the time it takes for the operation to complete or the result it completes with, and no part of the thread falls into a wait state at any point.</p>
<p>Let&rsquo;s look at another example of a <em>synchronous</em> call that <em>blocks</em> a thread. Suppose we are building an application that compares the results of two Weather APIs to find their percent difference in temperature. In a blocking manner, we make a call to Weather API One and wait for the result. Once we get a result, we call Weather API Two and wait for its result.</p>
<p><img src="/introduction-to-node/SyncBlock.png" alt="Pictorial showing async/sync block time"></p>
<p>Allow me to note, it&rsquo;s important to recognize that not all synchronous calls are necessarily blocking. If a synchronous operation can manage to complete without blocking the thread or causing a wait state, it was non-blocking. Most of the time, synchronous calls will be blocking, and the time they take to complete will depend on a variety of factors, such as the speed of the API&rsquo;s servers, the end user&rsquo;s internet connection download speed, etc.</p>
<p>In the case of the image above, we had to wait quite a while to retrieve the first results from API One. Thereafter, we had to wait equally as long to get a response from API Two. While waiting for both responses, the user would notice our application hang, and this is bad for User Experience.</p>
<p>In the case of a non-blocking call, we&rsquo;d have something like this:</p>
<p><img src="/introduction-to-node/AsyncNonBlock.png" alt="Non-Blocking Ops"></p>
<p>You can clearly see how much faster we concluded execution. Rather than wait on API One and then wait on API Two, we could wait for both of them to complete at the same time, and achieve our results almost 50% faster. Notice, once we called API One and started waiting for its response, we also called API Two and began waiting for its response at the same time as One.</p>
<p>At this point, before moving into more concrete and tangible examples, it is important to mention that, for ease, the term <em>&ldquo;Synchronous&rdquo;</em> is generally shortened to &ldquo;Sync&rdquo;, and the term <em>&ldquo;Asynchronous&rdquo;</em> is generally shortened to &ldquo;Async&rdquo;. You will see this notation used in method/function names.</p>
<h3 id="callback-functions">Callback Functions</h3>
<p>You might be wondering, &ldquo;if we can handle a call asynchronously, how do we know when that call is finished and we have a response?&rdquo; Generally, we pass in as an argument to our async method a callback function, and that method will &ldquo;call back&rdquo; that function at a later time with a response. I&rsquo;m using ES5 functions here, but we&rsquo;ll update to ES6 standards later.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">asyncAddFunction</span>(<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">callback</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">callback</span>(<span style="color:#a6e22e">a</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">b</span>); <span style="color:#75715e">//This callback is the one passed in to the function call below.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">asyncAddFunction</span>(<span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">4</span>, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">sum</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">//Here we have the sum, 2 + 4 = 6.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>Such a function is called a &ldquo;Higher-Order Function&rdquo; since it takes a function (our callback) as an argument. Alternatively, a callback function might take in an error object and a response object as arguments, and present them when the async function is complete. We&rsquo;ll see this later with Express. When we called <code>asyncAddFunction(...)</code>, you&rsquo;ll notice we supplied a callback function for the callback parameter from the method definition. This function is an <em>anonymous</em> function (it does not have a name) and is written using the <em>Expression Syntax</em>. The method definition, on the other hand, is a function statement. It&rsquo;s not anonymous because it actually has a name (that being &ldquo;asyncAddFunction&rdquo;).</p>
<p>Some may note confusion since, in the method definition, we do supply a name, that being &ldquo;callback&rdquo;. However, the anonymous function passed in as the third parameter to <code>asyncAddFunction(...)</code> does not know about the name, and so it remains anonymous. We also can&rsquo;t execute that function at a later point by name, we&rsquo;d have to go through the async calling function again to fire it.</p>
<p>As an example of a synchronous call, we can use the Node.js <code>readFileSync(...)</code> method. Again, we&rsquo;ll be moving to ES6+ later.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">fs</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;fs&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">data</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">fs</span>.<span style="color:#a6e22e">readFileSync</span>(<span style="color:#e6db74">&#39;/example.txt&#39;</span>); <span style="color:#75715e">// The thread will be blocked here until complete.
</span></span></span></code></pre></div><p>If we were doing this asynchronously, we&rsquo;d pass in a callback function which would fire when the the async operation was complete.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">fs</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;fs&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">data</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">fs</span>.<span style="color:#a6e22e">readFile</span>(<span style="color:#e6db74">&#39;/example.txt&#39;</span>, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>, <span style="color:#a6e22e">data</span>) { <span style="color:#75715e">//Move on, this will fire when ready.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#66d9ef">if</span>(<span style="color:#a6e22e">err</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Data: &#39;</span>, <span style="color:#a6e22e">data</span>);
</span></span><span style="display:flex;"><span>}); 
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Keep executing below, don&#39;t wait on the data.
</span></span></span></code></pre></div><p>If you have never seen <code>return</code> used in that manner before, we are just saying to stop function execution so we don&rsquo;t print the data object if the error object is defined. We could also have just wrapped the log statement in an <code>else</code> clause.</p>
<p>Like our <code>asyncAddFunction(...)</code>, the code behind the <code>fs.readFile(...)</code> function would be something along the lines of:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">readFile</span>(<span style="color:#a6e22e">path</span>, <span style="color:#a6e22e">callback</span>) {
</span></span><span style="display:flex;"><span> <span style="color:#75715e">// Behind the scenes code to read a file stream.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span> <span style="color:#75715e">// The data variable is defined here up here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span> <span style="color:#a6e22e">callback</span>(<span style="color:#66d9ef">undefined</span>, <span style="color:#a6e22e">data</span>); <span style="color:#75715e">//Or, callback(err, undefined);
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Allow us to look at one last implementation of an async function call. This will help to solidify the idea of callback functions being fired at a later point in time, and it will help us to understand the execution of a typical Node.js program.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">setTimeout</span>(<span style="color:#66d9ef">function</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}, <span style="color:#ae81ff">1000</span>);
</span></span></code></pre></div><p>The <code>setTimeout(...)</code> method takes a callback function for the first parameter which will be fired after the number of milliseconds specified as the second argument has occurred.</p>
<p>Let&rsquo;s look at a more complex example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Initiated program.&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">setTimeout</span>(<span style="color:#66d9ef">function</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;3000 ms (3 sec) have passed.&#39;</span>);
</span></span><span style="display:flex;"><span>}, <span style="color:#ae81ff">3000</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">setTimeout</span>(<span style="color:#66d9ef">function</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;0 ms (0 sec) have passed.&#39;</span>);
</span></span><span style="display:flex;"><span>}, <span style="color:#ae81ff">0</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">setTimeout</span>(<span style="color:#66d9ef">function</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;1000 ms (1 sec) has passed.&#39;</span>);
</span></span><span style="display:flex;"><span>}, <span style="color:#ae81ff">1000</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Terminated program&#39;</span>);
</span></span></code></pre></div><p>The output we receive is:</p>
<pre tabindex="0"><code>Initiated program.
Terminated program.
0 ms (0 sec) have passed.
1000 ms (1 sec) has passed.
3000 ms (3 sec) have passed.
</code></pre><p>You can see that the first log statement runs as expected. Instantaneously, the last log statement prints to the screen, for that happens before 0 seconds have surpassed after the second <code>setTimeout(...)</code>. Immediately thereafter, the second, third, and first <code>setTimeout(...)</code> methods execute.</p>
<p>If Node.js was not non-blocking, we&rsquo;d see the first log statement, wait 3 seconds to see the next, instantaneously see the third (the 0-second <code>setTimeout(...)</code>, and then have to wait one more second to see the last two log statements. The non-blocking nature of Node makes all timers start counting down from the moment the program is executed, rather than the order in which they are typed.</p>
<p>It is important to note that just because you see a callback function does not necessarily mean there is an asynchronous call in the code.</p>
<h3 id="promises-over-callbacks">Promises over Callbacks</h3>
<p>Callbacks can quickly become messy in JavaScript, especially multiple nested callbacks. We are familiar with passing a callback as an argument to a function, but Promises allow us to tack, or attach, a callback to an object returned from a function. This would allow us to handle multiple async calls in a more elegant manner.</p>
<p>As an example, suppose we are making an API call, and our function, not so uniquely named &lsquo;<code>makeAPICall(...)</code>&rsquo;, takes a URL and a callback.</p>
<p>Our function, <code>makeAPICall(...)</code>, would be defined as</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#a6e22e">path</span>, <span style="color:#a6e22e">callback</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// Attempt to make API call to path argument.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">callback</span>(<span style="color:#66d9ef">undefined</span>, <span style="color:#a6e22e">res</span>); <span style="color:#75715e">// Or, callback(err, undefined);
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>and we would call it with:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err1</span>, <span style="color:#a6e22e">res1</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">if</span>(<span style="color:#a6e22e">err1</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err1</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// ... 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>});
</span></span></code></pre></div><p>If we wanted to make another API call using the response from the first, we would have to nest both callbacks. Suppose I need to inject the <code>userName</code> property from the <code>res1</code> object into the path of the second API call. We would have:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err1</span>, <span style="color:#a6e22e">res1</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">if</span>(<span style="color:#a6e22e">err1</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err1</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/newExample/&#39;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">res1</span>.<span style="color:#a6e22e">userName</span>, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err2</span>, <span style="color:#a6e22e">res2</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span>(<span style="color:#a6e22e">err2</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err2</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">res2</span>);
</span></span><span style="display:flex;"><span>  });
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p><em>Note: The ES6+ method to inject the <code>res1.userName</code> property rather than string concatenation would be to use &ldquo;Template Strings&rdquo;. That way, rather than encapsulate our string in quotes (&rsquo;, or &ldquo;), we would use backticks (`), located beneath the Escape key on your keyboard. Then, we would use the notation <code>${}</code> to embed any JS expression inside the brackets. In the end, our earlier path would be: <code>/newExample/${res.UserName}</code>, wrapped in backticks.</em></p>
<p>It is clear to see that this method of nesting callbacks can quickly become quite inelegant, so-called the &ldquo;JavaScript Pyramid of Doom&rdquo;. Jumping in, if we were using promises rather than callbacks, we could refactor our code from the first example as such:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>).<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) { <span style="color:#75715e">// Success callback.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>) { <span style="color:#75715e">// Failure callback.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error:&#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>The first argument to the <code>then()</code> function is our success callback, and the second argument is our failure callback. Alternatively, we could lose the second argument to <code>.then()</code>, and call <code>.catch()</code> instead. Arguments to <code>.then()</code> are optional, and calling <code>.catch()</code> would be equivalent to <code>.then(successCallback, null)</code>.</p>
<p>Using <code>.catch()</code>, we have:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>).<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) { <span style="color:#75715e">// Success callback.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}).<span style="color:#66d9ef">catch</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>) {  <span style="color:#75715e">// Failure Callback
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>We can also restructure this for readability:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>)
</span></span><span style="display:flex;"><span>  .<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// ...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  })
</span></span><span style="display:flex;"><span>  .<span style="color:#66d9ef">catch</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>  });
</span></span></code></pre></div><p>It is important to note that we can&rsquo;t just tack a <code>.then()</code> call on to any function and expect it to work. The function we are calling has to actually return a promise, a promise that will fire the <code>.then()</code> when that async operation is complete. In this case, <code>makeAPICall(...)</code> will do it&rsquo;s thing, firing either the <code>then()</code> block or the <code>catch()</code> block when completed.</p>
<p>To make <code>makeAPICall(...)</code> return a Promise, we assign a function to a variable, where that function is the Promise constructor. Promises can be either <em>fulfilled</em> or <em>rejected</em>, where fulfilled means that the action relating to the promise completed successfully, and rejected meaning the opposite. Once the promise is either fulfilled or rejected, we say it has <em>settled</em>, and while waiting for it to settle, perhaps during an async call, we say that the promise is <em>pending</em>.</p>
<p>The Promise constructor takes in one callback function as an argument, which receives two parameters - <code>resolve</code> and <code>reject</code>, which we will call at a later point in time to fire either the success callback in <code>.then()</code>, or the <code>.then()</code> failure callback, or <code>.catch()</code>, if provided.</p>
<p>Here is an example of what this looks like:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">examplePromise</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> Promise(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">resolve</span>, <span style="color:#a6e22e">reject</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// Do whatever we are going to do and then make the appropiate call below:
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">resolve</span>(<span style="color:#e6db74">&#39;Happy!&#39;</span>); <span style="color:#75715e">// - Everything worked.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">reject</span>(<span style="color:#e6db74">&#39;Sad!&#39;</span>); <span style="color:#75715e">// - We noticed that something went wrong.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>})<span style="color:#f92672">:</span>
</span></span></code></pre></div><p>Then, we can use:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">examplePromise</span>.<span style="color:#a6e22e">then</span>(<span style="color:#75715e">/* Both callback functions in here */</span>);
</span></span></code></pre></div><p>Notice, however, that <code>examplePromise</code> can&rsquo;t take any arguments. That kind of defeats the purpose, so we can return a promise instead.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#a6e22e">path</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> Promise(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">resolve</span>, <span style="color:#a6e22e">reject</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Make our async API call here.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">if</span> (<span style="color:#75715e">/* All is good */</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">resolve</span>(<span style="color:#a6e22e">res</span>); <span style="color:#75715e">//res is the response, would be defined above.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">reject</span>(<span style="color:#a6e22e">err</span>); <span style="color:#75715e">//err is error, would be defined above.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  });
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Promises really shine to improve the structure, and subsequently, elegance, of our code with the concept of &ldquo;Promise Chaining&rdquo;. This would allow us to return a new Promise inside a <code>.then()</code> clause, so we could attach a second <code>.then()</code> thereafter, which would fire the appropriate callback from the second promise.</p>
<p>Refactoring our multi API URL call above with Promises, we get:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>).<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) { <span style="color:#75715e">// First response callback. Fires on success to &#39;/example&#39; call.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">`/newExample/</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">UserName</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>); <span style="color:#75715e">// Returning new call allows for Prmoise Chaining.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>) { <span style="color:#75715e">// First failure callback. Fires if there is a failure calling with &#39;/example&#39;.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error:&#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>}).<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) { <span style="color:#75715e">// Second response callback. Fires on success to returned &#39;/newExample/...&#39; call.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">res</span>);
</span></span><span style="display:flex;"><span>}, <span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>) { <span style="color:#75715e">// Second failure callback. Fire if there is a failure calling with &#39;/newExample/...&#39;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error:&#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>Notice that we first call <code>makeAPICall('/example')</code>. That returns a promise, and so we attach a <code>.then()</code>. Inside that <code>then()</code>, we return a new call to <code>makeAPICall(...)</code>, which, in and of itself, as seen earlier, returns a promise, permitting us chain on a new <code>.then()</code> after the first.</p>
<p>Like above, we can restructure this for readability, and remove the failure callbacks for a generic <code>catch()</code> all clause. Then, we can follow the DRY Principle (Don&rsquo;t Repeat Yourself), and only have to implement error handling once.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>)
</span></span><span style="display:flex;"><span>  .<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) { <span style="color:#75715e">// Like earlier, fires with success and response from &#39;/example&#39;.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">`/newExample/</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">UserName</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>); <span style="color:#75715e">// Returning here lets us chain on a new .then(). 
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>   })
</span></span><span style="display:flex;"><span>  .<span style="color:#a6e22e">then</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">res</span>) { <span style="color:#75715e">// Like earlier, fires with success and response from &#39;/newExample&#39;.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">res</span>);
</span></span><span style="display:flex;"><span>   })
</span></span><span style="display:flex;"><span>  .<span style="color:#66d9ef">catch</span>(<span style="color:#66d9ef">function</span>(<span style="color:#a6e22e">err</span>) { <span style="color:#75715e">// Generic catch all method. Fires if there is an err with either earlier call.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>   });
</span></span></code></pre></div><h3 id="es6-const-vs-let">ES6 Const vs. Let</h3>
<p>Throughout all of our examples, we have been employing ES5 functions and the old <code>var</code> keyword. While millions of lines of code still run today employing those ES5 methods, it is useful to update to current ES6+ standards, and we&rsquo;ll refactor some of our code above. Let&rsquo;s start with <code>const</code> and <code>let</code>.</p>
<p>You might be used to declaring a variable with the <code>var</code> keyword:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">pi</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3.14</span>;
</span></span></code></pre></div><p>With ES6+ standards, we could make that either</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">let</span> <span style="color:#a6e22e">pi</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3.14</span>;
</span></span></code></pre></div><p>or</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">pi</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">3.14</span>;
</span></span></code></pre></div><p>where <code>const</code> means &ldquo;constant&rdquo; - a value that cannot be reassigned to later. (Except for object properties - we&rsquo;ll cover that soon. Also, variables declared <code>const</code> are <em>not</em> immutable, only the reference to the variable is.)</p>
<p>In old JavaScript, block scopes, such as those in <code>if</code>, <code>while</code>, <code>{}</code>. <code>for</code>, etc. did not affect <code>var</code> in any way, and this is quite different to more statically typed languages like Java or C++. That is, the scope of <code>var</code> is the entire enclosing function - and that could be global (if placed outside a function), or local (if placed within a function). To demonstrate this, see the following example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">myFunction</span>() {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">num</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">5</span>;
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">num</span>); <span style="color:#75715e">// 5
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;--&#39;</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">for</span>(<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">i</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>; <span style="color:#a6e22e">i</span> <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">10</span>; <span style="color:#a6e22e">i</span><span style="color:#f92672">++</span>)
</span></span><span style="display:flex;"><span>  {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">num</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">i</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">num</span>); <span style="color:#75715e">//num becomes 0 - 9
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  }
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;--&#39;</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">num</span>); <span style="color:#75715e">// 9
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">i</span>); <span style="color:#75715e">// 10
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myFunction</span>();
</span></span></code></pre></div><p>Output:</p>
<pre tabindex="0"><code>5
---
0
1 2 3 ... 7 8 9
---
9
10
</code></pre><p>The important thing to notice here is that defining a new <code>var num</code> inside the <code>for</code> scope directly affected the <code>var num</code> outside and above the <code>for</code>. This is because <code>var</code>&rsquo;s scope is always that of the enclosing function, and not a block.</p>
<p>Again, by default, <code>var i</code> inside <code>for()</code> defaults to <code>myFunction</code>&rsquo;s scope, and so we can access <code>i</code> outside the loop and get 10.</p>
<p>In terms of assigning values to variables, <code>let</code> is equivalent to <code>var</code>, it&rsquo;s just that <code>let</code> has block scoping, and so the anomalies that occurred with <code>var</code> above will not happen.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">myFunction</span>() {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">let</span> <span style="color:#a6e22e">num</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">5</span>;
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">num</span>); <span style="color:#75715e">// 5
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#66d9ef">for</span>(<span style="color:#66d9ef">let</span> <span style="color:#a6e22e">i</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>; <span style="color:#a6e22e">i</span> <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">10</span>; <span style="color:#a6e22e">i</span><span style="color:#f92672">++</span>)
</span></span><span style="display:flex;"><span>  {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">let</span> <span style="color:#a6e22e">num</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">i</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;--&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">num</span>); <span style="color:#75715e">// num becomes 0 - 9
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  }
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;--&#39;</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">num</span>); <span style="color:#75715e">// 5
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">i</span>); <span style="color:#75715e">// undefined, ReferenceError
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Looking at the <code>const</code> keyword, you can see that we attain an error if we try to reasign to it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">c</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">299792458</span>; <span style="color:#75715e">// Fact: The constant &#34;c&#34; is the speed of light in a vacuum in meters per second.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">c</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">10</span>; <span style="color:#75715e">// TypeError: Assignment to constant variable. 
</span></span></span></code></pre></div><p>Things become interesting when we assign a <code>const</code> variable to an object:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myObject</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;Jane Doe&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is illegal: TypeError: Assignment to constant variable.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">myObject</span> <span style="color:#f92672">=</span> { 
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;John Doe&#39;</span>
</span></span><span style="display:flex;"><span>};
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// This is legal. console.log(myObject.name) -&gt; John Doe
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">myObject</span>.<span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;John Doe&#39;</span>;
</span></span></code></pre></div><p>As you can see, only the reference in memory to the object assigned to a <code>const</code> object is immutable, not the value its self.</p>
<h3 id="es6-arrow-functions">ES6 Arrow Functions</h3>
<p>You might be used to creating a function like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">printHelloWorld</span>() {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Hello, World!&#39;</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>With arrow functions, that would become:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">printHelloWorld</span> <span style="color:#f92672">=</span> () =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Hello, World!&#39;</span>);
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>Suppose we have a simple function that returns the square of a number:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">squareNumber</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">x</span>) =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">x</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">x</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">squareNumber</span>(<span style="color:#ae81ff">5</span>); <span style="color:#75715e">// We can call an arrow function like an ES5 functions. Returns 25.
</span></span></span></code></pre></div><p>You can see that, just like with ES5 functions, we can take in arguments with parentheses, we can use normal return statements, and we can call the function just like any other.</p>
<p>It&rsquo;s important to note that, while parentheses are required if our function takes no arguments (like with <code>printHelloWorld()</code> above), we can drop the parentheses if it only takes one, so our earlier <code>squareNumber()</code> method definition can be rewritten as:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">squareNumber</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">x</span> =&gt; { <span style="color:#75715e">// Notice we have dropped the parentheses for we only take in one argument.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">x</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">x</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Whether you choose to encapsulate a single argument in parentheses or not is a matter of personal taste, and you will likely see developers use both methods.</p>
<p>Finally, if we only want to implicitly return one expression, as with <code>squareNumber(...)</code> above, we can put the return statement in line with the method signature:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">squareNumber</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">x</span> =&gt; <span style="color:#a6e22e">x</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">x</span>;
</span></span></code></pre></div><p>That is,</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">test</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">c</span>) =&gt; <span style="color:#a6e22e">expression</span> 
</span></span></code></pre></div><p>is the same as</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">test</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">c</span>) =&gt; { <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">expression</span> }
</span></span></code></pre></div><p>Note, when using the above shorthand to implicitly return an object, things become obscure. What stops JavaScript from believing the brackets within which we are required to encapsulate our object is not our function body? To get around this, we wrap the object&rsquo;s brackets in parentheses. This explicitly lets JavaScript know that we are indeed returning an object, and we are not just defining a body.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">test</span> <span style="color:#f92672">=</span> () =&gt; ({<span style="color:#a6e22e">pi</span><span style="color:#f92672">:</span> <span style="color:#ae81ff">3.14</span>});
</span></span></code></pre></div><p>To help solidify the concept of ES6 functions, we&rsquo;ll refactor some of our earlier code allowing us to compare the differences between both notations.</p>
<p><code>asyncAddFunction(...)</code>, from above, could be refactored from:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">asyncAddFunction</span>(<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">callback</span>){
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">callback</span>(<span style="color:#a6e22e">a</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">b</span>); 
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>to:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">aysncAddFunction</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">callback</span>) =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">callback</span>(<span style="color:#a6e22e">a</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">b</span>);
</span></span><span style="display:flex;"><span>};
</span></span></code></pre></div><p>or even to:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">aysncAddFunction</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">a</span>, <span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">callback</span>) =&gt; <span style="color:#a6e22e">callback</span>(<span style="color:#a6e22e">a</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">b</span>); <span style="color:#75715e">// This will return callback(a + b).
</span></span></span></code></pre></div><p>When calling the function, we could pass an arrow function in for the callback:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">asyncAddFunction</span>(<span style="color:#ae81ff">10</span>, <span style="color:#ae81ff">12</span>, <span style="color:#a6e22e">sum</span> =&gt; { <span style="color:#75715e">// No parentheses because we only take one argument.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">sum</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>It is clear to see how this method improves code readability. To show you just one case, we can take our old ES5 Promise based example above, and refactor it to use arrow functions.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">&#39;/example&#39;</span>)
</span></span><span style="display:flex;"><span>  .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">res</span> =&gt; <span style="color:#a6e22e">makeAPICall</span>(<span style="color:#e6db74">`/newExample/</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">UserName</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>))
</span></span><span style="display:flex;"><span>  .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">res</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">res</span>))
</span></span><span style="display:flex;"><span>  .<span style="color:#66d9ef">catch</span>(<span style="color:#a6e22e">err</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error: &#39;</span>, <span style="color:#a6e22e">err</span>));
</span></span></code></pre></div><p>Now, there are some caveats with arrow functions. For one, they do not bind a <code>this</code> keyword. Suppose I have the following object:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;John Doe&#39;</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">greeting</span><span style="color:#f92672">:</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Hi. My name is </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">name</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>You might expect a call to <code>Person.greeting()</code> will return &lsquo;Hi. My name is John Doe.&rsquo; Instead, we get: &lsquo;Hi. My name is undefined.&rsquo;. That is because arrow functions do not have a <code>this</code>, and so attempting to use <code>this</code> inside an arrow function defaults to the <code>this</code> of the enclosing scope, and the enclosing scope of the <code>Person</code> object is <code>window</code>, in the browser, or <code>module.exports</code> in Node.</p>
<p>To prove this, if we use the same object again, but set the <code>name</code> property of the global <code>this</code> to something like &lsquo;Jane Doe&rsquo;, then <code>this.name</code> in the arrow function returns &lsquo;Jane Doe&rsquo;, because the global <code>this</code> is within the enclosing scope, or is the parent of the <code>Person</code> object.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Jane Doe&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;John Doe&#39;</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">greeting</span><span style="color:#f92672">:</span> () =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Hi. My name is </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">name</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">Person</span>.<span style="color:#a6e22e">greeting</span>(); <span style="color:#75715e">// Hi. My name is Jane Doe
</span></span></span></code></pre></div><p>This is known as &lsquo;Lexical Scoping&rsquo;, and we can get around it by using the so-called &lsquo;Short Syntax&rsquo;, which is where we lose the colon and the arrow as to refactor our object as such:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">Person</span> <span style="color:#f92672">=</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">name</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;John Doe&#39;</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">greeting</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`Hi. My name is </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">name</span><span style="color:#e6db74">}</span><span style="color:#e6db74">.`</span>);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">Person</span>.<span style="color:#a6e22e">greeting</span>() <span style="color:#75715e">//Hi. My name is John Doe.
</span></span></span></code></pre></div><h3 id="javascript-events">JavaScript Events</h3>
<p>An Event is an action that occurs to which you have the ability to respond. Suppose you are building a login form for your application. When the user presses the &ldquo;submit&rdquo; button, you can react to that event via an &ldquo;event handler&rdquo; in your code - typically a function. When this function is defined as the event handler, we say we are &ldquo;registering an event handler&rdquo;. The event handler for the submit button click will likely check the the formatting of the input provided by the user, sanitize it to prevent such attacks as SQL Injections or Cross Site Scripting, and then check to see if that username and password combination exits within a database to authenticate a user and serve them a token.</p>
<p>Since this is an article about Node, we&rsquo;ll focus on the (Node Event Model)[&ldquo;https://nodejs.org/docs/latest-v5.x/api/events.html&rdquo;].</p>
<p>We can use the <code>events</code> module from Node to emit and react to specific events. Any object that emits an event is an instance of the <code>EventEmitter</code> class.</p>
<p>We can emit an event by calling the <code>emit()</code> method and we listen for that event via the <code>on()</code> method, both of which are exposed through the <code>EventEmitter</code> class.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">EventEmitter</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;events&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myEmitter</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">EventEmitter</span>();
</span></span></code></pre></div><p>With <code>myEmitter</code> now an instance of the <code>EventEmitter</code> class, we can access <code>emit()</code> and <code>on()</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">EventEmitter</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;events&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myEmitter</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">EventEmitter</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myEmitter</span>.<span style="color:#a6e22e">on</span>(<span style="color:#e6db74">&#39;someEvent&#39;</span>, () =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;The &#34;someEvent&#34; event was fired (emitted)&#39;</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myEmitter</span>.<span style="color:#a6e22e">emit</span>(<span style="color:#e6db74">&#39;someEvent&#39;</span>);
</span></span></code></pre></div><p>The second parameter to <code>myEmitter.on()</code> is the callback function that will fire when the event is emitted - this is the event handler. The first parameter is the name of the event, which can be anything we like, although the camelCase naming convention is recommended.</p>
<p>Additionally, the event handler can take any number of arguments, which are passed down when the event is emitted:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">EventEmitter</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;events&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myEmitter</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">EventEmitter</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myEmitter</span>.<span style="color:#a6e22e">on</span>(<span style="color:#e6db74">&#39;someEvent&#39;</span>, (<span style="color:#a6e22e">data</span>) =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`The &#34;someEvent&#34; event was fired (emitted) with data: </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">data</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myEmitter</span>.<span style="color:#a6e22e">emit</span>(<span style="color:#e6db74">&#39;someEvent&#39;</span>, <span style="color:#e6db74">&#39;This is the data payload&#39;</span>);
</span></span></code></pre></div><p>By using inheritance, we can expose the <code>emit()</code> and <code>on()</code> methods from &lsquo;EventEmitter&rsquo; to any class. This is done by creating a Node.js class, and using the <code>extends</code> reserved keyword to inherit the properties available on <code>EventEmitter</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">EventEmitter</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;events&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">MyEmitter</span> <span style="color:#66d9ef">extends</span> <span style="color:#a6e22e">EventEmitter</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#75715e">// This is my class. I can emit events from a MyEmitter object.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>Suppose I am building a vehicle collision notification program. When a vehicle collides with an object, external sensors will detect the crash, executing the <code>collide(...)</code> function and passing to it the aggregated sensor data as a nice JavaScript Object. This function will emit a <code>collision</code> event, notifying the vendor of the crash.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">EventEmitter</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;events&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Vehicle</span> <span style="color:#66d9ef">extends</span> <span style="color:#a6e22e">EventEmitter</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">collide</span>(<span style="color:#a6e22e">collisionStatistics</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">emit</span>(<span style="color:#e6db74">&#39;collision&#39;</span>, <span style="color:#a6e22e">collisionStatistics</span>)
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">myVehicle</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Vehicle</span>();
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myVehicle</span>.<span style="color:#a6e22e">on</span>(<span style="color:#e6db74">&#39;collision&#39;</span>, <span style="color:#a6e22e">collisionStatistics</span> =&gt; {
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">note</span>(<span style="color:#e6db74">&#39;WARNING! Vehicle Impact Detected: &#39;</span>, <span style="color:#a6e22e">collisionStatistics</span>);
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">notifyVendor</span>(<span style="color:#a6e22e">collisionStatistics</span>);
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">myVehicle</span>.<span style="color:#a6e22e">collide</span>({ ... });
</span></span></code></pre></div><p>This is a convoluted example for we could just put the code within the event handler inside the collide function of the class, but it demonstrates how the Node Event Model functions nonetheless. Note that some tutorials will show the <code>util.inherits()</code> method of permitting an object to emit events. That has been deprecated in favor of ES6 Classes and <code>extends</code>.</p>
<h3 id="the-node-package-manager">The Node Package Manager</h3>
<p>When programming with Node and JavaScript, it&rsquo;ll be quite common to hear about <code>npm</code>. Npm is a package manager which does just that - permits the downloading of third-party packages that solve common problems in JavaScript. Other solutions, such as Yarn, Npx, Grunt, and Bower exist as well, but in this section, we&rsquo;ll focus only on <code>npm</code> and how you can install dependencies for your application through a simple Command Line Interface (CLI) using it.</p>
<p>Let&rsquo;s start simple, with just <code>npm</code>. Visit <a href="https://www.npmjs.com/">https://www.npmjs.com/</a> to view all of the packages available from NPM. When you start a new project that will depend on NPM Packages, you&rsquo;ll have to run <code>npm init</code> through the terminal in your project&rsquo;s root directory. You will be asked a series of questions which will be used to create a <code>package.json</code> file. This file stores all of your dependencies - modules that your application depends on to function, scripts - pre-defined terminal commands to run tests, build the project, start the development server, etc., and more.</p>
<p>To install a package, simply run <code>npm install [package-name] --save</code>. The <code>save</code> flag will ensure the package and its version is logged in the <code>package.json</code> file. Since <code>npm</code> version 5, dependencies are saved by default, so <code>--save</code> may be omitted. You will also notice a new <code>node_modules</code> folder, containing the code for that package you just installed. This can also be shortened to just <code>npm i [package-name]</code>. As a helpful note, the <code>node_modules</code> folder should never be included in a GitHub repository due to its size. Whenever you clone a repo from GitHub (or any other version management system), be sure to run the command <code>npm install</code> to go out and fetch all the packages defined in the <code>package.json</code> file, creating the <code>node_modules</code> directory automatically. You can also install a package at a specific version: <code>npm i [package-name]@1.10.1 --save</code>, for example.</p>
<p>Removing a package is similar to installing one: <code>npm remove [package-name]</code>.</p>
<p>You can also install a package globally. This package will be available across all projects, not just the one your working on. You do this with the <code>-g</code> flag after <code>npm i [package-name]</code>. This is commonly used for CLIs, such as Google Firebase and Heroku. Despite the ease this method presents, it is generally considered bad practice to install packages globally, for they are not saved in the <code>package.json</code> file, and if another developer attempts to use your project, they won&rsquo;t attain all the required dependencies from <code>npm install</code>.</p>
<h3 id="apis--json">APIs &amp; JSON</h3>
<p>APIs are a very common paradigm in programming, and even if you are just starting out in your career as a developer, APIs and their usage, especially in web and mobile development, will likely come up more often than not.</p>
<p>An API is an <em>Application Programming Interface</em>, and it is basically a method by which two decoupled systems may communicate with each other. In more technical terms, an API permits a system or computer program (usually a server) to receive requests and send appropriate responses (to a client, also known as a host).</p>
<p>Suppose you are building a weather application. You need a way to geocode a user&rsquo;s address into a latitude and longitude, and then a way to attain the current or forecasted weather at that particular location.</p>
<p>As a developer, you want to focus on building your app and monetizing it, not putting the infrastructure in place to geocode addresses or placing weather stations in every city.</p>
<p>Luckily for you, companies like Google and OpenWeatherMap have already put that infrastructure in place, you just need a way to talk to it - that is where the API comes in. While, as of now, we have developed a very abstract and ambiguous definition of the API, bear with me. We&rsquo;ll be getting to tangible examples soon.</p>
<p>Now, it costs money for companies to develop, maintain, and secure that aforementioned infrastructure, and so it is common for corporations to sell you access to their API. This is done with that is known as an API key, a unique alphanumeric identifier associating you, the developer, with the API. Every time you ask the API to send you data, you pass along your API key. The server can then authenticate you and keep track of how many API calls you are making, and you will be charged appropriately. The API key also permits <em>Rate-Limiting</em> or <em>API Call Throttling</em> (a method of throttling the number of API calls in a certain timeframe as to not overwhelm the server, preventing DOS attacks - Denial of Service). Most companies, however, will provide a free quota, giving you, as an example, 25000 free API calls a day before charging you.</p>
<p>Up to this point, we have established that an API is a method by which two computer programs can communicate with each other. If a server is storing data, such as a website, and your browser makes a request to download the code for that site, that was the API in action.</p>
<p>Let us look at a more tangible example, and then we&rsquo;ll look at a more real-world, technical one. Suppose you are eating out at a restaurant for dinner. You are equivalent to the client, sitting at the table, and the chef in the back is equivalent to the server.</p>
<p>Since you will never directly talk to the chef, there is no way for him/her to receive your request (for what order you would like to make) or for him/her to provide you with your meal once you order it. We need someone in the middle. In this case, it&rsquo;s the waiter, analogous to the API. The API provides a medium with which you (the client) may talk to the server (the chef), as well as a set of rules for how that communication should be made (the menu - one meal is allowed two sides, etc.)</p>
<p>Now, how do you actually talk to the API (the waiter)? You might speak English, but the chef might speak Spanish. Is the waiter expected to know both languages to translate? What if a third person comes in who only speaks Mandarin? What then? Well, all clients and servers have to agree to speak a common language, and in computer programming, that language is JSON, pronounced JAY-sun, and it stands for JavaScript Object Notation.</p>
<p>At this point, we don&rsquo;t quite know what JSON looks like. It&rsquo;s not a computer programming language, it&rsquo;s just, well, a language, like English or Spanish, that everyone (everyone being computers) understands on a guaranteed basis. It&rsquo;s guaranteed because it&rsquo;s a standard, notably <em>RFC 8259</em>, the <em>JavaScript Object Notation (JSON) Data Interchange Format</em> by the Internet Engineering Task Force (IETF).</p>
<p>Even without formal knowledge of what JSON actually is and what it looks like (we&rsquo;ll see in an upcoming article in this series), we can go ahead introduce a technical example operating on the Internet today that employs APIs and JSON. APIs and JSON are not just something you can choose to use, it&rsquo;s not equivalent to one out of a thousand JavaScript frameworks you can pick to do the same thing. It is <em>THE</em> standard for data exchange on the web.</p>
<p>Suppose you are building a travel website that compares prices for aircraft, rental car, and hotel ticket prices. Let us walk through, step-by-step, on a high level, how we would build such an application. Of course, we need our User Interface, the front-end, but that is out of scope for this article.</p>
<p>We want to provide our users with the lowest price booking method. Well, that means we need to somehow attain all possible booking prices, and then compare all of the elements in that set (perhaps we store them in an array) to find the smallest element (known as the infimum in mathematics.)</p>
<p>How will we get this data? Well, suppose all of the booking sites have a database full of prices. Those sites will provide an API, which exposes the data in those databases for use by you. You will call each API for each site to attain all possible booking prices, store them in your own array, find the lowest or minimum element of that array, and then provide the price and booking link to your user. We&rsquo;ll ask the API to query its database for the price in JSON, and it will respond with said price in JSON to us. We can then use, or parse, that accordingly. We have to parse it because APIs will return JSON as a string, not the actual JavaScript data type of JSON. This might not make sense now, and that&rsquo;s okay. We&rsquo;ll be covering it more in a future article.</p>
<p>Also, note that just because something is called an API does not necessarily mean it operates on the web and sends and receives JSON. The Java API, for example, is just the list of classes, packages, and interfaces that are part of the Java Development Kit (JDK), providing programming functionality to the programmer.</p>
<p>Okay. We know we can talk to a program running on a server by way of an Application Programming Interface, and we know that the common language with which we do this is known as JSON. But in the web development and networking world, everything has a protocol. What do we actually do to make an API call, and what does that look like code-wise? That&rsquo;s where HTTP Requests enter the picture, the HyperText Transfer Protocol, defining how messages are formatted and transmitted across the Internet. Once we have an understanding of HTTP (and HTTP verbs, you&rsquo;ll see that in the next section), we can look into actual JavaScript frameworks and methods (like <code>fetch()</code>) offered by the <em>JavaScript API</em> (similar to the Java API), that actually allow us to make API calls.</p>
<h3 id="http-and-http-requests">HTTP and HTTP Requests</h3>
<p>HTTP is the HyperText Transfer Protocol. It is the underlying protocol that determines how messages are formatted as they are transmitted and received across the web. Let&rsquo;s think about what happens when, for example, you attempt to load the home page of Smashing Magazine in your web browser.</p>
<p>You type the website URL (Uniform Resource Locator) in the URL bar, where the DNS server (Domain Name Server, out of scope for this article) resolves the URL into the appropriate IP Address. The browser makes a request, called a GET Request, to the Web Server to, well, GET the underlying HTML behind the site. The Web Server will respond with a message such as &ldquo;OK&rdquo;, and then will go ahead and send the HTML down to the browser where it will be parsed and rendered accordingly.</p>
<p>There are a few things to note here. First, the GET Request, and then the &ldquo;OK&rdquo; response. Suppose you have a specific database, and you want to write an API to expose that database to your users. Suppose the database contained books the user wants to read. Then there are four fundamental operations your user may want to perform on this database, that is, Create a record, Read a record, Update a record, or Delete a record, known collectively as CRUD operations.</p>
<p>Let&rsquo;s look at the Read operation for a moment. Without incorrectly assimilating or conflating the notion of a web server and a database, that Read operation is very similar to your web browser attempting to <em>get</em> the site from the server, just as to read a record is to <em>get</em> the record from the database.</p>
<p>This is known as an HTTP Request. You are making a request to some server somewhere to <em>get</em> some data, and, as such, the request is appropriately named &ldquo;GET&rdquo;, capitalization being a standard way to denote such requests.</p>
<p>What about the Create portion of CRUD? Well, when talking about HTTP Requests, that is known as a POST request. Just as you might <em>post</em> a message on a social media platform, you might also <em>post</em> a new record to a database. Another such option is PUT, <em>putting</em> a new record in the database.</p>
<p>CRUD&rsquo;s Update allows us to use either PUT or PATCH. You may be wondering, &ldquo;You just said that PUT can be used to create a resource. Why then are you saying it can also be used to update a resource?&rdquo; Well, HTTP&rsquo;s PUT will either create a new record or will update/replace the old one.</p>
<p>Let&rsquo;s look at this a bit more in detail, and then we&rsquo;ll get to PATCH.</p>
<p>An API generally works by making HTTP requests to specific routes, in a URL. Suppose we are making an API to store a user&rsquo;s booklist. Then we might be able to view those books at the URL <code>.../books</code>. A POST requests to <code>.../books</code> will create a new book with whatever properties you define (think id, title, ISBN, author, publishing data, etc.) at the <code>.../books</code> route. It doesn&rsquo;t matter what the underlying data structure is that stores all the books at <code>.../books</code> right now. We just care that the API exposes that endpoint (accessed through the route) to manipulate data. The prior sentence was key: A POST request CREATES a new book at the <code>...books/</code> route. The difference between PUT and POST, then, is that PUT will create a new book (as with POST) if no such book exists, <em>or, it will replace an existing book</em> if the book already exists within that aforementioned data structure.</p>
<p>Suppose each book has the following properties: id, title, ISBN, author, hasRead (boolean).</p>
<p>Then to add a new book, as seen earlier, we would make a POST request to <code>.../books</code>. If we wanted to completely update or replace a book, we would make a PUT request to <code>.../books/id</code> where <code>id</code> is the ID of the book we want to replace.</p>
<p>While PUT completely replaces an existing book, PATCH updates something having to do with a specific book, perhaps modifying the <code>hasRead</code> boolean property we defined above.</p>
<p>It can be difficult to see the meaning of this right now, for thus far, we&rsquo;ve established everything in theory but haven&rsquo;t seen any tangible code that actually makes an HTTP request. We shall, however, get to that soon.</p>
<p>There is one last fundamental CRUD operation and it&rsquo;s called Delete. As you would expect, the name of such an HTTP Request is &ldquo;DELETE&rdquo;, and it works much the same as PATCH, requiring the book&rsquo;s ID be provided in a route.</p>
<p>We have learned thus far, then, that routes are specific URLs to which you make an HTTP Request, and that endpoints are functions the API provides, doing something to the data it exposes. That is, the endpoint is a programming language function located on the other end of the route, and it performs whatever HTTP Request you specified. We also learned that there exist such terms as POST, GET, PUT, PATCH, DELETE, and more (known as HTTP verbs) that actually specify what requests you are making to the API. Like JSON, these HTTP Request Methods are Internet standards as defined by the Internet Engineering Task Force (IETF), most notably, <a href="https://tools.ietf.org/html/rfc7231#section-4">RFC 7231, Section Four: Request Methods</a>, and <a href="https://tools.ietf.org/html/rfc5789#section-2">RFC 5789, Section Two: Patch Method</a>, where RFC is an acronym for Request for Comments.</p>
<p>So, we might make a GET request to the URL <code>.../books/id</code> where the ID passed in is known as a parameter. We could make a POST, PUT, or PATCH request to <code>.../books</code> to create a resource or to <code>.../books/id</code> to modify/replace/update a resource. And we can also make a DELETE request to <code>.../books/id</code> to delete a specific book.</p>
<p>A full list of HTTP Request Methods can be found here: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods</a></p>
<p>It is also important to note that after making an HTTP Request, we&rsquo;ll receive a response. The specific response is determined by how we build the API, but you should always receive a status code. Earlier, we said that when your web browser requests the HTML from the web server, it&rsquo;ll respond with &ldquo;OK&rdquo;. That is known as an HTTP Status Code, more specifically, HTTP 200 OK. The status code just specifies how the operation or action specified in the endpoint (remember, that&rsquo;s our function that does all the work) completed. HTTP Status Codes are sent back by the server, and there are probably many you are familiar with, such as 404 Not Found (the resource or file could not be found, this would be like making a GET request to <code>.../books/id</code> where no such ID exists.)</p>
<p>A complete list of HTTP Status Codes can be found here: <a href="https://httpstatuses.com/">https://httpstatuses.com/</a></p>
<h3 id="mongodb">MongoDB</h3>
<p>MongoDB is a non-relational, NoSQL database similar to the Firebase Real-time Database. You will talk to the database via a Node package such as the MongoDB Native Driver or Mongoose.</p>
<p>In MongoDB, data is stored in JSON, which is quite different to relational databases such as MySQL, PostgreSQL, or SQLite. Both are called databases, with SQL Tables called Collections, SQL Table Rows called Documents, and SQL Table Columns called Fields.</p>
<p>We will use the MongoDB Database in an upcoming article in this series when we create our very first Bookshelf API. The fundamental CRUD Operations listed above can be performed on a MongoDB Database.</p>
<p>It&rsquo;s recommended that you read through the MongoDB Docs: <a href="https://docs.mongodb.com/manual/introduction/">https://docs.mongodb.com/manual/introduction/</a> to learn how to create a live database on an Atlas Cluster and make CRUD Operations to it with the MongoDB Native Driver. In the next article of this series, we will learn how to set up a local database and a cloud production database.</p>
<h3 id="building-a-command-line-node-application">Building a Command Line Node Application</h3>
<p>When building out an application, you will see many authors dump their entire code base at the beginning of the article, and then attempt to explain each line thereafter. In this text, I&rsquo;ll take a different approach. I&rsquo;ll explain my code line-by-line, building the app as we go. I won&rsquo;t worry about modularity or performance, I won&rsquo;t split the codebase into separate files, and I won&rsquo;t follow the DRY Principle or attempt to make the code reusable. When just learning, it is useful to make things as simple as possible, and so that is the approach I will take here.</p>
<p>If you want to see the finished code, visit the GitHub Repository HERE.</p>
<p>If you want to see the refactored version of the code making use of some of the properties in the former paragraph, visit THIS GitHub Repository.</p>
<p>Let us be clear about what we are building. We won&rsquo;t be concerned with user input, and so we won&rsquo;t make use of packages like <a href="https://www.npmjs.com/package/yargs">Yargs</a>. We also won&rsquo;t be building our own API. That will come in a later article in this series when we make use of the Express Web Application Framework. I take this approach as to not conflate Node.js with the power of Express and APIs since most tutorials do. Rather, I&rsquo;ll provide one method (of many) by which to call and receive data from an external API which utilizes a third-party JavaScript library. The API we&rsquo;ll be calling is a Weather API, which we&rsquo;ll acess from Node and dump its output to the terminal, perhaps with some formatting, known as &ldquo;pretty-printing&rdquo;. I&rsquo;ll cover the entire process, including how to set up the API and attain API Key, the steps of which provide the correct results as of January 2019.</p>
<p>We&rsquo;ll be using the OpenWeatherMap API for this project, so to get started, navigate to <a href="https://home.openweathermap.org/users/sign_up">https://home.openweathermap.org/users/sign_up</a> and create an account with the form. Once logged in, find the API Keys menu item on the dashboard page, located at <a href="https://home.openweathermap.org/api_keys">https://home.openweathermap.org/api_keys</a>. If you just created an account, you&rsquo;ll have to pick a name for your API Key and hit &ldquo;Generate&rdquo;. It could take at least 2 hours for your new API Key to be functional and associated with your account.</p>
<p>Before we start building out the application, we&rsquo;ll visit the API Documentation (<a href="https://openweathermap.org/current">https://openweathermap.org/current</a>) to learn how to format our API Key. In this project, we&rsquo;ll be specifying a zip code and a country code to attain the weather information at that location.</p>
<p>From the docs, we can see that the method by which we do this is to provide the following URL:</p>
<p><code>api.openweathermap.org/data/2.5/weather?zip={zip code},{country code}</code></p>
<p>Into which we could input data:</p>
<p><code>api.openweathermap.org/data/2.5/weather?zip=94040,us</code></p>
<p>Now, before we can actually attain relevant data from this API, we&rsquo;ll need to provide our new API Key as a query parameter:</p>
<p><code>api.openweathermap.org/data/2.5/weather?zip=94040,us&amp;appid={YOUR_API_KEY}</code></p>
<p>For now, copy that URL into a new tab in your web browser, replacing the <code>{YOUR_API_KEY}</code> placeholder with the API Key you obtained earlier when you registered for an account.</p>
<p>The text you can see is actually JSON - the agreed upon language of the web as discussed earlier.</p>
<p>To inspect this further, hit <code>Ctrl + Shift + I</code> in Google Chrome to open the Chrome Developer tools, and then navigate to the Network tab. At present, there should be no data here.</p>
<p><img src="/introduction-to-node/net-activity.png" alt="Empty Chrome Dev Tools Network Tab"></p>
<p>To actually monitor network data, reload the page, and watch the tab be populated with useful information. Click the first link as depicted in the image below.</p>
<p><img src="/introduction-to-node/pop-net-activity.png" alt="Populated Chrome Dev Tools Network Tab"></p>
<p>Once you click on that link, we can actually view HTTP specific information, such as the headers. Headers are sent in the response from the API (you can also, in some cases, send your own headers to the API, or you can even create your own custom headers (often prefixed with <code>x-</code>) to send back when building your own API), and just contain extra information that either the client or server may need.</p>
<p>In this case, you can see that we made an HTTP GET Request to the API, and it responded with an HTTP Status 200 OK. You can also see that the data sent back was in JSON, as listed under the &ldquo;Response Headers&rdquo; section.</p>
<p><img src="/introduction-to-node/complete-diagram.png" alt="Populated Chrome Dev Tools Network Tab"></p>
<p>If you hit the preview tab, you can actually view the JSON as a JavaScript Object. The text version you can see in your browser is a string, for JSON is always transmitted and received across the web as a string. That&rsquo;s why we have to parse the JSON in our code, to get it into a more readable format - in this case (and in pretty much every case) - a JavaScript Object.</p>
<p>You can also use the Google Chrome Extension &ldquo;JSON View&rdquo; to do this automatically.</p>
<p>To start building out our application, I&rsquo;ll open a terminal and make a new root directory and then <code>cd</code> into it. Once inside, I&rsquo;ll create a new <code>app.js</code> file, run <code>npm init</code> to generate a <code>package.json</code> file with the default settings, and then open Visual Studio Code</p>
<pre tabindex="0"><code>mkdir command-line-weather-app &amp;&amp; cd command-line-weather-app
touch app.js
npm init
code .
</code></pre><p>Thereafter, I&rsquo;ll download Axios, verify it has been added to my <code>package.json</code> file, and note that the <code>node_modules</code> folder has been created successfully.</p>
<p>In the browser, you can see that we made a GET Request by hand by manually typing the proper URL into the URL Bar. <a href="https://www.npmjs.com/package/axios">Axios</a> is what will allow me to do that inside of Node.</p>
<p>Starting now, all of the following code will be located inside of the <code>app.js</code> file, each snippet placed after the other.</p>
<p>The first thing I&rsquo;ll do is require the Axios package we installed earlier with</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">axios</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;axios&#39;</span>);
</span></span></code></pre></div><p>We now have access to Axios, and can make relevant HTTP Requests, via the <code>axios</code> constant.</p>
<p>Generally, our API calls will be dynamic - in this case, we might want to inject different zip codes and country codes into our URL. So, I&rsquo;ll be creating constant variables for each part of the URL, and then put them together with ES6 Template Strings. First, we have the part of our URL that will never change as well as our API Key:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;https://api.openweathermap.org/data/2.5/weather?zip=&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_KEY</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your API Key Here&#39;</span>;
</span></span></code></pre></div><p>I&rsquo;ll also assign our zip code and country code. Since we are not expecting user input and are rather hard coding the data, I&rsquo;ll make these constant as well, although, in many cases, it will be more useful to use <code>let</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">LOCATION_ZIP_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;90001&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">COUNTRY_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;us&#39;</span>;
</span></span></code></pre></div><p>We now need to put these variables together into one URL to which we can use Axios to make GET Requests to:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">ENTIRE_API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">`</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_URL</span><span style="color:#e6db74">}${</span><span style="color:#a6e22e">LOCATION_ZIP_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">,</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">COUNTRY_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">&amp;appid=</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_KEY</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>;
</span></span></code></pre></div><p>Here is the contents of our <code>app.js</code> file up to this point:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">axios</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;axios&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// API specific settings.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;https://api.openweathermap.org/data/2.5/weather?zip=&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_KEY</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your API Key Here&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">LOCATION_ZIP_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;90001&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">COUNTRY_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;us&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">ENTIRE_API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">`</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_URL</span><span style="color:#e6db74">}${</span><span style="color:#a6e22e">LOCATION_ZIP_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">,</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">COUNTRY_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">&amp;appid=</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_KEY</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>;
</span></span></code></pre></div><p>All that is left to do is to actually use <code>axios</code> to make a GET Request to that URL. For that, we&rsquo;ll use the <code>get(url)</code> method provided by <code>axios</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">axios</span>.<span style="color:#a6e22e">get</span>(<span style="color:#a6e22e">ENTIRE_API_URL</span>)
</span></span></code></pre></div><p><code>axios.get(...)</code> actually returns a Promise, and the success callback function will take in a response argument which will allow us to access the response from the API - the same thing you saw in the browser. I&rsquo;ll also add a <code>.catch()</code> clause to catch any errors.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">axios</span>.<span style="color:#a6e22e">get</span>(<span style="color:#a6e22e">ENTIRE_API_URL</span>)
</span></span><span style="display:flex;"><span>    .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">response</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">response</span>))
</span></span><span style="display:flex;"><span>    .<span style="color:#66d9ef">catch</span>(<span style="color:#a6e22e">error</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error&#39;</span>, <span style="color:#a6e22e">error</span>));
</span></span></code></pre></div><p>If we now run this code with <code>node app.js</code> in the terminal, you will be able to see the full response we get back. However, suppose you just want to see the temperature for that zip code - then most of that data in the response is not useful to you. Axios actually returns the response from the API in the data object, which is a property of the response. That means the response from the server is actually located at <code>response.data</code>, so let&rsquo;s print that instead in the callback function: <code>console.log(response.data)</code>.</p>
<p>Now, we said that web servers always deal with JSON as a string, and that is true. You might notice, however, that <code>response.data</code> is already an object (evident by running <code>console.log(typeof response.data)</code>) - we didn&rsquo;t have to parse it with <code>JSON.parse()</code>. That is because Axios already takes care of this for us behind the scenes.</p>
<p>The output in the terminal from running <code>console.log(response.data)</code> can be formatted - &ldquo;pretty-printed&rdquo; - by running <code>console.log(JSON.stringify(response.data, undefined, 2))</code>. <code>JSON.stringify()</code> converts a JSON object into a string, and take in the object, a filter, and the number of characters by which to indent by when printing. You can see the response this provides:</p>
<pre tabindex="0"><code>{
  &#34;coord&#34;: {
    &#34;lon&#34;: -118.24,
    &#34;lat&#34;: 33.97
  },
  &#34;weather&#34;: [
    {
      &#34;id&#34;: 800,
      &#34;main&#34;: &#34;Clear&#34;,
      &#34;description&#34;: &#34;clear sky&#34;,
      &#34;icon&#34;: &#34;01d&#34;
    }
  ],
  &#34;base&#34;: &#34;stations&#34;,
  &#34;main&#34;: {
    &#34;temp&#34;: 288.21,
    &#34;pressure&#34;: 1022,
    &#34;humidity&#34;: 15,
    &#34;temp_min&#34;: 286.15,
    &#34;temp_max&#34;: 289.75
  },
  &#34;visibility&#34;: 16093,
  &#34;wind&#34;: {
    &#34;speed&#34;: 2.1,
    &#34;deg&#34;: 110
  },
  &#34;clouds&#34;: {
    &#34;all&#34;: 1
  },
  &#34;dt&#34;: 1546459080,
  &#34;sys&#34;: {
    &#34;type&#34;: 1,
    &#34;id&#34;: 4361,
    &#34;message&#34;: 0.0072,
    &#34;country&#34;: &#34;US&#34;,
    &#34;sunrise&#34;: 1546441120,
    &#34;sunset&#34;: 1546476978
  },
  &#34;id&#34;: 420003677,
  &#34;name&#34;: &#34;Lynwood&#34;,
  &#34;cod&#34;: 200
}
</code></pre><p>Now, it is clear to see that the temperature we are looking for is located on the <code>main</code> property of the <code>response.data</code> object, so we can access it by calling <code>response.data.main.temp</code>. Let&rsquo;s look at out application&rsquo;s code up to now:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">axios</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;axios&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// API specific settings.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;https://api.openweathermap.org/data/2.5/weather?zip=&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_KEY</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your API Key Here&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">LOCATION_ZIP_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;90001&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">COUNTRY_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;us&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">ENTIRE_API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">`</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_URL</span><span style="color:#e6db74">}${</span><span style="color:#a6e22e">LOCATION_ZIP_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">,</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">COUNTRY_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">&amp;appid=</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_KEY</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">axios</span>.<span style="color:#a6e22e">get</span>(<span style="color:#a6e22e">ENTIRE_API_URL</span>)
</span></span><span style="display:flex;"><span>    .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">response</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">main</span>.<span style="color:#a6e22e">temp</span>))
</span></span><span style="display:flex;"><span>    .<span style="color:#66d9ef">catch</span>(<span style="color:#a6e22e">error</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error&#39;</span>, <span style="color:#a6e22e">error</span>));
</span></span></code></pre></div><p>The temperature we get back is actually in Kelvin, which is a temperature scale generally used in Physics, Chemistry, and Thermodynamics due to the fact that it provides an &ldquo;absolute zero&rdquo; point, which is the temperature at which all thermal motion of all inner particles cease. We just need to convert this to Fahrenheit or Celcius with the formulas below:</p>
<p><code>F = K * 9/5 - 459.67</code>
<code>C = K - 273.15</code></p>
<p>Let&rsquo;s update our success callback to print the new data with this conversion. We&rsquo;ll also add in a proper sentence for the purposes of User Experience:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#a6e22e">axios</span>.<span style="color:#a6e22e">get</span>(<span style="color:#a6e22e">ENTIRE_API_URL</span>)
</span></span><span style="display:flex;"><span>    .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">response</span> =&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Getting the current temperature and the city from the response object.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">kelvinTemperature</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">main</span>.<span style="color:#a6e22e">temp</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">cityName</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">name</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">countryName</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">sys</span>.<span style="color:#a6e22e">country</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Making K to F and K to C conversions.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">fahrenheitTemperature</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">kelvinTemperature</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">9</span><span style="color:#f92672">/</span><span style="color:#ae81ff">5</span>) <span style="color:#f92672">-</span> <span style="color:#ae81ff">459.67</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">celciusTemperature</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">kelvinTemperature</span> <span style="color:#f92672">-</span> <span style="color:#ae81ff">273.15</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Building the final message.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">message</span> <span style="color:#f92672">=</span> (
</span></span><span style="display:flex;"><span>            <span style="color:#e6db74">`Right now, in \
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">cityName</span><span style="color:#e6db74">}</span><span style="color:#e6db74">, </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">countryName</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> the current temperature is \
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">fahrenheitTemperature</span>.<span style="color:#a6e22e">toFixed</span>(<span style="color:#ae81ff">2</span>)<span style="color:#e6db74">}</span><span style="color:#e6db74"> deg F or \
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">celciusTemperature</span>.<span style="color:#a6e22e">toFixed</span>(<span style="color:#ae81ff">2</span>)<span style="color:#e6db74">}</span><span style="color:#e6db74"> deg C.`</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">/\s+/g</span>, <span style="color:#e6db74">&#39; &#39;</span>)
</span></span><span style="display:flex;"><span>        );
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">message</span>);
</span></span><span style="display:flex;"><span>    })
</span></span><span style="display:flex;"><span>    .<span style="color:#66d9ef">catch</span>(<span style="color:#a6e22e">error</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error&#39;</span>, <span style="color:#a6e22e">error</span>));
</span></span></code></pre></div><p>The parentheses around the <code>message</code> variable are not required, they just look nice - similar to when working with JSX in React. The backslashes stop the template string from formatting a new line, and the <code>replace()</code> String prototype method gets rid of white space using Regular Expressions (RegEx). The <code>toFixed()</code> Number prototype methods rounds a float to a specific number of decimal places - in this case, two.</p>
<p>With that, our final <code>app.js</code> looks as follows:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">axios</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;axios&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// API specific settings.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;https://api.openweathermap.org/data/2.5/weather?zip=&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">API_KEY</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;Your API Key Here&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">LOCATION_ZIP_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;90001&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">COUNTRY_CODE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;us&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">ENTIRE_API_URL</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">`</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_URL</span><span style="color:#e6db74">}${</span><span style="color:#a6e22e">LOCATION_ZIP_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">,</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">COUNTRY_CODE</span><span style="color:#e6db74">}</span><span style="color:#e6db74">&amp;appid=</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">API_KEY</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">axios</span>.<span style="color:#a6e22e">get</span>(<span style="color:#a6e22e">ENTIRE_API_URL</span>)
</span></span><span style="display:flex;"><span>    .<span style="color:#a6e22e">then</span>(<span style="color:#a6e22e">response</span> =&gt; {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Getting the current temperature and the city from the response object.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">kelvinTemperature</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">main</span>.<span style="color:#a6e22e">temp</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">cityName</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">name</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">countryName</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">response</span>.<span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">sys</span>.<span style="color:#a6e22e">country</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Making K to F and K to C conversions.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">fahrenheitTemperature</span> <span style="color:#f92672">=</span> (<span style="color:#a6e22e">kelvinTemperature</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">9</span><span style="color:#f92672">/</span><span style="color:#ae81ff">5</span>) <span style="color:#f92672">-</span> <span style="color:#ae81ff">459.67</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">celciusTemperature</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">kelvinTemperature</span> <span style="color:#f92672">-</span> <span style="color:#ae81ff">273.15</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Building the final message.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">message</span> <span style="color:#f92672">=</span> (
</span></span><span style="display:flex;"><span>            <span style="color:#e6db74">`Right now, in \
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">cityName</span><span style="color:#e6db74">}</span><span style="color:#e6db74">, </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">countryName</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> the current temperature is \
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">fahrenheitTemperature</span>.<span style="color:#a6e22e">toFixed</span>(<span style="color:#ae81ff">2</span>)<span style="color:#e6db74">}</span><span style="color:#e6db74"> deg F or \
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">celciusTemperature</span>.<span style="color:#a6e22e">toFixed</span>(<span style="color:#ae81ff">2</span>)<span style="color:#e6db74">}</span><span style="color:#e6db74"> deg C.`</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">/\s+/g</span>, <span style="color:#e6db74">&#39; &#39;</span>)
</span></span><span style="display:flex;"><span>        );
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">message</span>);
</span></span><span style="display:flex;"><span>    })
</span></span><span style="display:flex;"><span>    .<span style="color:#66d9ef">catch</span>(<span style="color:#a6e22e">error</span> =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">&#39;Error&#39;</span>, <span style="color:#a6e22e">error</span>));
</span></span></code></pre></div><h3 id="conclusion">Conclusion</h3>
<p>We have learned a lot about how Node works in this article, from the differences between synchronous and asynchronous requests, to callback functions, to new ES6 features, events, package managers, APIs, JSON, and the HyperText Transfer Protocol, Non-Relational Databases, and we even built our own command line application utilizing most of that new found knowledge.</p>
<p>In future articles in this series, we&rsquo;ll take an in-depth look at the Call Stack, the Event Loop, and Node APIs, we&rsquo;ll talk about Cross-Origin Resource Sharing (CORS), and we&rsquo;ll build a Full Stack Bookshelf API utilizing databases, endpoints, user authentication, tokens, server-side template rendering, and more.</p>
<p>From here, start building your own Node applications, read the Node documentation, go out and find interesting APIs or Node Modules and implement them yourself. The world is your oyster and you have at your fingertips access to the largest network of knowledge on the planet - the Internet. Use it to your advantage.</p>
]]></content>
        </item>
        
    </channel>
</rss>
