<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Bernhard Häussermann</title>
    <description>The latest articles on DEV Community by Bernhard Häussermann (@bhaeussermann).</description>
    <link>https://dev.to/bhaeussermann</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F679220%2Fa8ff24e2-ac06-4302-bf6a-f569958e3bf8.jpeg</url>
      <title>DEV Community: Bernhard Häussermann</title>
      <link>https://dev.to/bhaeussermann</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/bhaeussermann"/>
    <language>en</language>
    <item>
      <title>Creating a weak dictionary in .NET</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Thu, 10 Nov 2022 04:14:15 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/creating-a-weak-dictionary-in-net-1fo</link>
      <guid>https://dev.to/bhaeussermann/creating-a-weak-dictionary-in-net-1fo</guid>
      <description>&lt;p&gt;I once found myself in need of a dictionary for temporarily holding references to some objects. This dictionary was to hold weak references to its values so that said values would become eligible for garbage collection once they were no longer needed.&lt;/p&gt;

&lt;p&gt;Such a &lt;code&gt;WeakDictionary&lt;/code&gt; would be useful when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;you need a temporary handle to objects having a known key, and&lt;/li&gt;
&lt;li&gt;your code isn't aware of when these objects fall out of use (i.e. you can't remove the entries explicitly).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The most obvious solution to this scenario would be to use a &lt;code&gt;Dictionary&amp;lt;KeyType, WeakReference&amp;gt;&lt;/code&gt; object. The &lt;a href="https://learn.microsoft.com/en-us/dotnet/api/system.weakreference?view=net-6.0"&gt;WeakReference&lt;/a&gt; will ensure that the dictionary doesn't contribute to the reference count of the object being referenced, allowing the object to be reclaimed by garbage collection even if it still has an entry in the dictionary.&lt;/p&gt;

&lt;p&gt;However, if our code isn't aware of when an entry can be safely removed, dictionary entries will accumulate over time. We would like for the dictionary to automatically remove any "stale" entries.&lt;/p&gt;

&lt;p&gt;In the spirit of &lt;a href="https://en.wikipedia.org/wiki/Test-driven_development"&gt;test-driven development&lt;/a&gt; here's an NUnit test that shows how we would expect the &lt;code&gt;WeakDictionary&lt;/code&gt; to behave.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Due to the way the garbage collector is implemented in .NET Core, there are a few hoops we need to jump through in order to ensure the test works. See this &lt;a href="https://stackoverflow.com/a/68836653/359765"&gt;StackOverflow answer&lt;/a&gt;. In particular, compiler optimizations need to be switched on in the test project, and the debugger must not be attached.&lt;/em&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;While searching for a solution, I quickly came across &lt;a href="https://stackoverflow.com/questions/2784291/good-implementation-of-weak-dictionary-in-net"&gt;this StackOverflow post&lt;/a&gt;. Whereas there were a lot of proposed answers, none of them were really what I was looking for. Each answer either:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;implemented a dictionary with weak references to the &lt;em&gt;keys&lt;/em&gt; as opposed to the &lt;em&gt;values&lt;/em&gt;, or&lt;/li&gt;
&lt;li&gt;relied on an explicit "purge" operation that needed to be called from time to time in order to clean up old references. I was looking for an implementation that would remove the entries of garbage collected objects immediately.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thankfully, though, the answers that were there provided me with the necessary ingredients that enabled me to create a dictionary that would work the intended way.&lt;/p&gt;

&lt;p&gt;A key ingredient is the &lt;a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2?view=net-6.0"&gt;ConditionalWeakTable&lt;/a&gt;. It is a dictionary-like data structure that holds weak references to its keys and removes an entry when the key is garbage collected. This is exactly what we need, except we need that behavior on the &lt;em&gt;value&lt;/em&gt; as opposed to the &lt;em&gt;key&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Using this &lt;code&gt;ConditionalWeakTable&lt;/code&gt; internally is a good start to our implementation of the &lt;code&gt;WeakDictionary&lt;/code&gt; as it may enable us to automatically remove dictionary entries when a value gets garbage collected: just add &lt;em&gt;values&lt;/em&gt; of the &lt;code&gt;WeakDictionary&lt;/code&gt; as &lt;em&gt;keys&lt;/em&gt; to the &lt;code&gt;ConditionalWeakTable&lt;/code&gt; and use it to properly maintain the entries in a separate dictionary.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;But how do we become aware of when an entry is removed from the &lt;code&gt;conditionalWeakTable&lt;/code&gt; in order to remove the corresponding entry from the &lt;code&gt;internalDictionary&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;Think about what happens when a key object of the &lt;code&gt;WeakDictionary&lt;/code&gt; is garbage collected:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The corresponding entry from &lt;code&gt;conditionalWeakTable&lt;/code&gt; is removed.&lt;/li&gt;
&lt;li&gt;This causes the reference count of the corresponding &lt;em&gt;value&lt;/em&gt; in the &lt;code&gt;conditionalWeakTable&lt;/code&gt; (typed as &lt;code&gt;object&lt;/code&gt;) to be decremented, causing it to be garbage collected as well (provided there are no other references to it).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Together with the fact that when an object is garbage collected, its finalizer (historically known as a destructor) will be invoked, this provides us with a way to act on this event by using a class such as the following:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We make this class be the &lt;em&gt;value&lt;/em&gt; type of &lt;code&gt;conditionalWeakTable&lt;/code&gt; and bring everything together in our class' &lt;code&gt;Add()&lt;/code&gt; method as follows:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This way when a value object is garbage collected, it will immediately be removed from &lt;code&gt;internalDictionary&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;All of the remaining methods of the &lt;code&gt;IDictionary&amp;lt;&amp;gt;&lt;/code&gt; interface are implemented to simply relay the method call to &lt;code&gt;internalDictionary&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We run the test and, sure enough, it passes!&lt;/p&gt;

&lt;p&gt;This gives us a useful data structure to use when we need key-based access to objects whose life-time we don't control.&lt;/p&gt;

&lt;p&gt;The complete implementation is available in the &lt;a href="https://github.com/bhaeussermann/weak-dictionary"&gt;GitHub repo&lt;/a&gt;.&lt;br&gt;
The library is available as a &lt;a href="https://www.nuget.org/packages/BernhardHaus.Collections.WeakDictionary"&gt;NuGet package&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
    </item>
    <item>
      <title>How to display an external link symbol next to links</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Fri, 05 Aug 2022 14:56:52 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/how-to-display-an-external-link-symbol-next-to-links-4dp3</link>
      <guid>https://dev.to/bhaeussermann/how-to-display-an-external-link-symbol-next-to-links-4dp3</guid>
      <description>&lt;p&gt;One day I was working on my personal portfolio site, adding external links towards some of the web apps that I had built. I was about to add some external link symbols to them when all of a sudden I realized... I'm not really sure how 😶.&lt;/p&gt;

&lt;p&gt;It's a convention of the web that you display the symbol next to any link that navigates to a different web site (i.e. a different domain than the one you are on).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;On some web sites the link will open in a new tab, but on many it won't. It can be argued that it's not for the web page to decide that the link should open in a new tab since the user can always intentionally do this by either middle-clicking the link or right-clicking and selecting "Open Link in New Tab".&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I turned to Google, looking for a "best-practice" way of displaying an external link symbol. Given how common the symbol is, one would expect there to be a standardized way of displaying it, right?&lt;/p&gt;

&lt;p&gt;It turns out there isn't 😶. I came across &lt;a href="https://stackoverflow.com/questions/1899772/most-robust-method-for-showing-icon-next-to-text"&gt;this StackOverflow post&lt;/a&gt; which asks exactly this question and contains a wide array of answers ranging from using a Unicode character, to using an icon library, to using an image. And yet, none of these answers completely satisfied me. I will discuss each type of method that was suggested (I'm linking each section to the relevant answer of that post) and why I had decided against it before I present the solution that I did end up using. Hopefully you will find that solution useful too.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;a href="https://stackoverflow.com/a/45806420/359765"&gt;Unicode character&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Using a Unicode character to represent the external link symbol would be the easiest solution by far. One suggestion is to use the &lt;a href="https://emojipedia.org/north-east-arrow/"&gt;North East Arrow&lt;/a&gt; Unicode character ↗. It looks pretty similar to the external link symbol, but alas, where's the box?!&lt;/p&gt;

&lt;p&gt;As of this writing, there are 144 697 different Unicode characters and one would think that there would be one to represent an external link! It turns out that this had been &lt;a href="https://www.unicode.org/L2/L2006/06268-ext-link.pdf"&gt;proposed&lt;/a&gt;, but the proposal was &lt;a href="https://www.unicode.org/alloc/nonapprovals.html"&gt;rejected&lt;/a&gt;. In my understanding the reason for the rejection was that the symbol does not represent "plain text" in the sense that it doesn't constitute the informational content on the page. To justify this practically, if you would copy and paste some text off of a web page, you wouldn't want the external link symbols to come along with the text. Ok, fair enough...&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;a href="https://stackoverflow.com/a/61104675/359765"&gt;Icon library&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;It turns out that some icon libraries, such as Font Awesome 5, do feature an external link symbol (see the &lt;a href="https://origin.fontawesome.com/v5/cheatsheet"&gt;Solid Icons cheat sheet&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YDi9lOti--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u34c8bdqcfwkkqwqttwf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YDi9lOti--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u34c8bdqcfwkkqwqttwf.png" alt="Image description" width="396" height="42"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It looks nice and you can easily adjust the symbol's size and color. This would probably have been my solution of choice if my project had an icon library included. However, it didn't, and I wasn't going to add an entire icon library to my project for just this one symbol.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;a href="https://stackoverflow.com/a/52058198/359765"&gt;Raster image&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;The answer featuring the image presents the following CSS code:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;I like the fact that it's expressed as a CSS rule because that way we aren't duplicating the code for the symbol, and it removes clutter from the HTML code.&lt;/p&gt;

&lt;p&gt;However, I don't like using raster images for things like icons. They don't remain crisp when viewed on a screen that is scaled (think of Retina displays), and if the user should increase the browser's zoom level, the image will also become blurred. There's also no easy way to change the image's color or to resize it without distorting it.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;a href="https://stackoverflow.com/a/65370632/359765"&gt;SVG image&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;The answer with the SVG image presents the following CSS code:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This CSS rule comes &lt;em&gt;very&lt;/em&gt; close to being my preferred solution. The only nit-pick I have is that the SVG code is completely shrouded as a base-64 string. I prefer including the SVG code as a URL-encoded XML string for transparency.&lt;/p&gt;

&lt;h2&gt;
  
  
  My preferred solution
&lt;/h2&gt;

&lt;p&gt;I ended up using the following CSS rule:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Which could be used as:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Granted, the fact that the SVG code has to be URL-encoded makes parts of it a bit cryptic, but at least you can still read it for the most part. You could even easily change the color should you want to (which is specified here as &lt;code&gt;stroke='#666'&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Ultimately, in a project that is already using an icon library I would first check to see if it includes an external link symbol and use that if it does. Otherwise I would use the aforementioned CSS rule. In both cases we are using vector graphics, so there are no issues related to resizing, and the color can easily be changed if desired.&lt;/p&gt;

</description>
      <category>html</category>
      <category>css</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Say "no" to silent failures in your methods</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Wed, 18 May 2022 18:48:41 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/say-no-to-silent-failures-in-your-methods-429e</link>
      <guid>https://dev.to/bhaeussermann/say-no-to-silent-failures-in-your-methods-429e</guid>
      <description>&lt;p&gt;One of my personal pet peeves when working on code is encountering logic that checks for some unexpected state and when that unexpected situation applies... does nothing. This is a classic case of sweeping mistakes under the carpet. Consider the following C# code:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;In this example we check the state of the order and if it is not in the expected state for processing, we do nothing. The problem here is that if the &lt;code&gt;ProcessOrder()&lt;/code&gt; method gets called on an order that is not in the right state for processing, this is most certainly a bug in the code that is calling the method. By ignoring the unexpected state, the &lt;code&gt;ProcessOrder()&lt;/code&gt; method is hiding the issue, making the underlying bug much harder to locate. &lt;/p&gt;

&lt;p&gt;This is because the code calling &lt;code&gt;ProcessOrder()&lt;/code&gt; will assume that after the method had been called, the order had been successfully processed. The if-condition in &lt;code&gt;ProcessOrder()&lt;/code&gt; makes it so that this assumption is not true so that the calling code might proceed interacting with an unprocessed order &lt;em&gt;as if&lt;/em&gt; it were a processed order. This would cause potential havoc, diverting attention away from the source of the problem.&lt;/p&gt;

&lt;p&gt;The core problem with &lt;code&gt;ProcessOrder()&lt;/code&gt; is that there are situations where the method would successfully return despite not having done what it was expected to do, i.e. processing the order.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Solution
&lt;/h2&gt;

&lt;p&gt;My personal rule of thumb for preventing this kind of situation is that a method should always do what it claims to do in its name (in this case processing the order), or otherwise throw an exception. If the method returns without an exception, this &lt;em&gt;must&lt;/em&gt; imply that the operation was completed successfully. This is the central point of this post, so I will state it explicitly:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A method must return without throwing an exception if &lt;em&gt;and only if&lt;/em&gt; it successfully did what it claims to do in its name. In any other case an exception must be thrown to indicate that what the method was expected to do could not be done.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Therefore a better implementation of the method above should look like:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  The Try-Parse Pattern
&lt;/h2&gt;

&lt;p&gt;There can be operations where it is not unusual that the operation can't be performed for one reason or another. That is, the reason for the operation not being able to be performed is &lt;em&gt;not&lt;/em&gt; due to an error or a programming bug, but merely a valid possible scenario. Since exceptions are supposed to be used for &lt;em&gt;exceptional&lt;/em&gt; cases only, such a situation calls for a different approach. Consider the following method signature:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The caller should expect that if the method successfully returns, it would provide a &lt;code&gt;Route&lt;/code&gt; leading from the provided source to the destination. If there is no such route, then based on the method's name, it should throw an exception because it wasn't able to "calculate the route". But what if the non-existence of a route is a common and valid use-case? We could make the method return &lt;code&gt;null&lt;/code&gt; if no route could be calculated, but this would amount to a false impression from the perspective of the caller that the route was calculated when that's not the case.&lt;/p&gt;

&lt;p&gt;This kind of scenario is often a good candidate for the &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern"&gt;try-parse pattern&lt;/a&gt;. Based on this pattern the method signature above would change into:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now, if no route is found, the method would return &lt;code&gt;false&lt;/code&gt; to indicate the fact. When it does, it's not "lying" about having performed its task because it did, in fact, &lt;em&gt;try&lt;/em&gt; to calculate the route like its name states.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern"&gt;Microsoft documentation about the try-parse pattern&lt;/a&gt; presents this as a much more performant alternative to throwing exceptions where exceptions would be thrown for common scenarios. Another benefit of using this pattern is that it makes it clear to the method caller that a certain case needs to be handled explicitly.&lt;/p&gt;

&lt;p&gt;Making a habit of ensuring all methods always do what their names say (or throwing an exception otherwise), makes it easier to reason about the code and helps make the source of programming bugs be more obvious when they occur.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>exceptions</category>
    </item>
    <item>
      <title>String Literals in JavaScript: Should I Use Double-quotes or Single-quotes?</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Mon, 09 May 2022 05:20:02 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/string-literals-in-javascript-should-i-use-double-quotes-or-single-quotes-7no</link>
      <guid>https://dev.to/bhaeussermann/string-literals-in-javascript-should-i-use-double-quotes-or-single-quotes-7no</guid>
      <description>&lt;p&gt;Most JavaScript (and TypeScript) developers know that the language allows expressing string literals using either double quotes (") or single quotes ('). Given that both ways of expressing strings are semantically equivalent, this leads to the question of which one is the “right” way.&lt;/p&gt;

&lt;p&gt;Generally, when it comes to coding style, it is advisable to conform to the convention of the particular language you are dealing with (for example, using camelCase for methods in JavaScript, but PascalCase in C#).&lt;/p&gt;

&lt;p&gt;Unfortunately, it appears that there is no official convention for string quotes when it comes to JavaScript. So, the next best thing we could do in deciding on the best style of quotes to use is to try and find out which convention is more common.&lt;/p&gt;

&lt;p&gt;Looking at some popular JavaScript projects on GitHub, I noted that &lt;a href="https://github.com/facebook/react"&gt;react&lt;/a&gt;, &lt;a href="https://github.com/moment/moment"&gt;moment&lt;/a&gt;, and &lt;a href="https://github.com/expressjs/express"&gt;express&lt;/a&gt; all use single quotes for strings. However, another popular project, &lt;a href="https://github.com/microsoft/tslib"&gt;tslib&lt;/a&gt;, uses double quotes 🙄. So, while it would seem that single quotes is more common, this metric is not entirely conclusive.&lt;/p&gt;

&lt;p&gt;The deciding factor that convinced me personally applies to web development using a JavaScript framework that uses HTML-templates, such as Angular or Vue.js. In particular, these frameworks allow us to use JavaScript expressions for HTML attribute values. Take for example the following:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Since HTML itself also happens to allow either double quotes or single quotes for delimiting attribute values, this kind of brings us back to the same debate. In the case of HTML attributes, however, I will always stick to double-quotes, since using single-quotes for attribute values is very uncommon and frankly just seems wrong.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So, given that we use double quotes for HTML attributes, the only way for us to use double quotes in a JavaScript expression would be like so:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;which for obvious reasons is pretty much out of the question. We are therefore basically forced to use single quotes for any string literal inside of a JavaScript expression.&lt;/p&gt;

&lt;p&gt;When it comes to coding conventions, applying a convention consistently is more important than using the “best” convention. If we are then going to use single quotes in JavaScript within HTML, we must do the same everywhere else for consistency’s sake. For this reason my personal final choice for JavaScript literals is to use single quotes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Coding style tooling
&lt;/h2&gt;

&lt;p&gt;Regardless of whether you are decided on using single quotes or double quotes in JavaScript, the more important issue is applying your convention consistently throughout the code base. &lt;a href="https://eslint.org/"&gt;ESLint&lt;/a&gt; is one tool that will help a great deal in enforcing a consistent coding style. You supply it with a config file specifying a list of rules describing your coding conventions, and it will indicate where your code is not conforming to the specified rules. See the following links to get started:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://eslint.org/docs/user-guide/getting-started"&gt;ESLint Getting Started Guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/typescript-eslint/typescript-eslint"&gt;TypeScript ESLint&lt;/a&gt;: tooling for adding TypeScript-support to ESLint&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://eslint.org/docs/user-guide/integrations"&gt;ESLint Integrations&lt;/a&gt;: locate the plugin for adding ESLint support to your favourite IDE&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Add the rule &lt;code&gt;quotes: ['error', 'single']&lt;/code&gt; to your &lt;em&gt;.eslintrc.js&lt;/em&gt; to make ESLint enforce single quotes.&lt;/p&gt;

&lt;p&gt;If you happen to have a lot of style transgressions in your code, know that some rule violations can be automatically fixed by ESLint (including strings literals using the wrong type of quote). Just run the &lt;em&gt;eslint&lt;/em&gt; command including the &lt;em&gt;--fix&lt;/em&gt; option, like so (adjust the &lt;em&gt;--ext&lt;/em&gt; option based on whether your code is in JavaScript or TypeScript):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;eslint -c .eslintrc.js --fix --ext .js ./
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I can also highly recommend &lt;a href="https://prettier.io/"&gt;Prettier&lt;/a&gt; for maintaining a consistent coding style and fixing up existing source code.&lt;/p&gt;

&lt;p&gt;Which one of the quote-styles you settle on using in your JavaScript / TypeScript code is not nearly as important as actually committing to that and applying the rule consistently. Consistent application of coding conventions is not to be underestimated since it can significantly reduce the cognitive overhead when reading the code. The use of tooling such as ESLint and Prettier can help a lot in ensuring the coding style remains consistent even with many developers contributing to the code base.&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Adding dark mode to your web app</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Fri, 11 Feb 2022 04:37:57 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/adding-dark-mode-to-your-web-app-86g</link>
      <guid>https://dev.to/bhaeussermann/adding-dark-mode-to-your-web-app-86g</guid>
      <description>&lt;p&gt;Dark mode in applications and web sites is a feature that seems to be becoming increasingly popular and ubiquitous. Thankfully, adding basic dark mode support to an existing web app that uses CSS is a fairly straightforward process. If you want to get started quickly, you've come to the right place! For a more in-depth and comprehensive guide, see the &lt;a href="https://css-tricks.com/a-complete-guide-to-dark-mode-on-the-web/#aa-using-custom-properties"&gt;Complete Guide to Dark Mode on the Web&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Demo App
&lt;/h2&gt;

&lt;p&gt;We will be adding dark mode support to a very simple web page that is backed by the following HTML code:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here is the CSS used to style the "item" elements:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here is what the page looks like in the browser:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ohn-1Iqp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvi9j0me48x7zgov2wna.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ohn-1Iqp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvi9j0me48x7zgov2wna.png" alt="Image description" width="701" height="390"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To test how well we are doing in dark mode out of the box, I first ensure that my browser's theme is set to the system theme (or "auto"), meaning it will display everything in light or dark mode based on the operating system setting (this should be the default). I then change the operating system setting to dark mode (assuming it was in light mode to begin with). The browser's window border changes accordingly, but the web page does not. We've got some work to do.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding basic dark mode support
&lt;/h2&gt;

&lt;p&gt;The quickest first step we can take is to tell the browser that our page supports both "light" and "dark" colours by adding the "color-scheme" meta tag to our page's &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt; element:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Refreshing the page reveals that we've already achieved a result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Gg4saSB6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6699vk2rrux22e1c7hl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Gg4saSB6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6699vk2rrux22e1c7hl.png" alt="Image description" width="880" height="491"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The elements that didn't have colours assigned to them in the CSS now take on the browser's default colours for the dark theme. This wasn't happening before because in the absence of this tag, the browser will assume that the page supports light mode only. Other benefits to specifying the "color-scheme" meta tag are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;unstyled controls (e.g. text boxes, check boxes) will also have their appearance changed to correspond to the selected theme, and&lt;/li&gt;
&lt;li&gt;even if all colours are specified in CSS, having this tag set will prevent a white background with black text flashing while the CSS is downloaded and the dark colours finally applied.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Adding the "color-scheme" meta tag was a quick win, but there's clearly more work left to do: we need to define the dark mode colours for the elements that do have their colours set via CSS. Colours in our CSS code can easily be overridden for dark mode using the &lt;code&gt;prefers-color-scheme&lt;/code&gt; media query:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We're looking much better now!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0hd5QXNA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wfqvbe1lttkv3sme6yvl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0hd5QXNA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wfqvbe1lttkv3sme6yvl.png" alt="Image description" width="880" height="491"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A quick way to find "dark mode" colours is to simply invert all the regular colours. This can easily be done by opening the Calculator, switching to Programmer mode and selecting hexadecimal. Then simply calculate &lt;code&gt;FFFFFF - xxxxxx&lt;/code&gt;, where &lt;code&gt;xxxxxx&lt;/code&gt; represents the regular colour in six hexadecimal digits. This provides a good starting point from which to tweak the colours further.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Making things managable
&lt;/h2&gt;

&lt;p&gt;On anything but the smallest of applications, CSS code like the above will prove to be a lot of work to maintain with future styling changes. Moving all the colours into CSS variables and setting these variables based on the current theme will result in more tidy CSS code that is much easier to maintain:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;By keeping the declaration of all the variables at the top of the file, the colours can now all be changed in one place.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dealing with images
&lt;/h2&gt;

&lt;p&gt;If your web app features images, they may not fit in well with the dark colours. In this case you may want to create a "dark" version of each image to use instead. If the image is specified in HTML, then switching between the "light" and "dark" version can all be done in HTML by replacing:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;with&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Allowing colour scheme selection via in-app setting
&lt;/h2&gt;

&lt;p&gt;There may be scenarios where a user would want to override the colour scheme in your app, regardless of their operating system setting. In this case you may want to offer options for "light", "dark", and "auto" (which would use the operating system setting).&lt;/p&gt;

&lt;p&gt;At this point CSS alone won't cut it; we're going to have to use some JavaScript to achieve this kind of functionality. One way would be to have the JavaScript code add or remove some special class (say &lt;code&gt;dark&lt;/code&gt;) to the top-most HTML element and set up the CSS rules to react to that:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The JavaScript code would have to watch the &lt;code&gt;prefers-color-schema&lt;/code&gt; media value in case the user has "auto" selected. The underlying code may look something like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Accessibility and improved battery life are just some of the reasons why dark mode has become a popular alternative colour scheme on most of the operating systems we use today; not to mention, it's hip and trendy 😎. Thankfully, implementing dark mode in web applications almost couldn't be easier, so why wait? 😉&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>css</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Adding TypeScript-support to your Node.js project</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Mon, 15 Nov 2021 11:18:08 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/adding-typescript-support-to-your-nodejs-project-3bfm</link>
      <guid>https://dev.to/bhaeussermann/adding-typescript-support-to-your-nodejs-project-3bfm</guid>
      <description>&lt;p&gt;Many Node.js projects will reach a level of complexity where we'll often find ourselves wondering what a certain object's structure looks like. We'll also have the need for early warnings about errors due to trying to access fields that don't exist or assuming different types from what they really are. These are good indications that you would derive a lot of benefit from using a type-checking system such as TypeScript. This article will look into how to make the transition from JavaScript to TypeScript in an existing project.&lt;/p&gt;

&lt;p&gt;TypeScript-support for Node.js is provided by the &lt;code&gt;typescript&lt;/code&gt; NPM package. The best way to implement this package will depend on your project's build tooling. If you have webpack set up, then the easiest way will be by using the &lt;code&gt;ts-loader&lt;/code&gt; package (see the "Setting up ts-loader for webpack" section below for this &lt;code&gt;ts-loader&lt;/code&gt; + &lt;code&gt;typescript&lt;/code&gt; setup). However, if you don't have a module bundler configured, then the simplest way to add TypeScript will be through the &lt;code&gt;tsc&lt;/code&gt; ("TypeScript compiler") command, which is included in the &lt;code&gt;typescript&lt;/code&gt; package. This &lt;code&gt;tsc&lt;/code&gt; setup is described next.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up TypeScript compiler (tsc)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;tsc&lt;/code&gt; is the official TypeScript transpiler which converts your TypeScript source files into JavaScript files that can be executed by Node.js or the browser. This section assumes you have a working Node.js project where you run your main js-file directly using &lt;code&gt;node&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The first order of business is adding the &lt;code&gt;typescript&lt;/code&gt; package to your project as a dev-dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The next step is to create a config file for &lt;code&gt;typescript&lt;/code&gt;. A good starting point is to generate the file using the command &lt;code&gt;npx tsc --init&lt;/code&gt;. Add the following properties to the &lt;code&gt;compilerOptions&lt;/code&gt; property in the generated file:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;"noImplicitAny": true&lt;/code&gt; — Disallows the use of the &lt;code&gt;any&lt;/code&gt; type - a common anti-pattern in TypeScript.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"allowJs": true&lt;/code&gt; — Allows us to have JavaScript (.js) files amongst the TypeScript (.ts) files. When we need to migrate an existing JavaScript project to TypeScript, this allows us to systematically convert files from JavaScript to TypeScript one at a time. Once the conversion is complete, this flag can be removed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"outDir": "dist"&lt;/code&gt; — The folder where the transpiled JavaScript files will be placed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"rootDir": "src"&lt;/code&gt; — The location of your TypeScript / JavaScript source code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After adding these properties the &lt;em&gt;tsconfig.json&lt;/em&gt; looks as follows:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;And just like that, the code is ready to be compiled! Just run the command &lt;code&gt;npx tsc&lt;/code&gt; and see the output files appear in the &lt;em&gt;dist&lt;/em&gt; folder.&lt;/p&gt;

&lt;p&gt;Before trying to run the compiled code, keep in mind that tsc outputs CommonJS-style JavaScript. This means that if your source code is written as ES modules, you need to change the &lt;code&gt;"type"&lt;/code&gt; property in your &lt;em&gt;package.json&lt;/em&gt; from &lt;code&gt;"module"&lt;/code&gt; to &lt;code&gt;"commonjs"&lt;/code&gt; in order to run the compiled code (tsc will still interpret your source code as ES modules). At this point the "main" .js file in the &lt;em&gt;dist&lt;/em&gt; folder should run successfully via the &lt;code&gt;node&lt;/code&gt; command: &lt;code&gt;node dist/my-app.js&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Source maps
&lt;/h2&gt;

&lt;p&gt;A side-effect of running the compiled code instead of running the source code directly is that stack traces of errors will refer to the line numbers inside the compiled code instead of in the source code, which is not very helpful. Luckily we can have tsc generate source map files which map each line in the compiled code to the corresponding line in the source code. These can be used to make our application report the correct line numbers in error stack traces.&lt;/p&gt;

&lt;p&gt;Getting tsc to generate the source map files is an easy matter of adding the &lt;code&gt;"sourceMap": true&lt;/code&gt; property to the &lt;code&gt;"compilerOptions"&lt;/code&gt; in &lt;em&gt;tsconfig.json&lt;/em&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Run &lt;code&gt;npx tsc&lt;/code&gt; again and note that in the &lt;em&gt;dist&lt;/em&gt; folder a &lt;em&gt;.js.map&lt;/em&gt; file is created for each compiled &lt;em&gt;.js&lt;/em&gt; file. However, we still need to make these mappings be interpreted at run-time. To do this, add the &lt;code&gt;source-map-support&lt;/code&gt; package as a run-time dependency. We also add its types declaration package for TypeScript as a dev-dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save source-map-support
npm install --save-dev @types/source-map-support
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;And activate it by adding the following to your main source file:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;Compile and run the application. Error stack traces will now refer to the lines in the source code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adapting script commands
&lt;/h2&gt;

&lt;p&gt;Creating script commands (in &lt;em&gt;package.json&lt;/em&gt;) for compiling and running the application is pretty simple:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"build": "tsc",
"run": "node dist/my-app.js",
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;For a streamlined developer experience we would want to have a command that will listen for source file changes and then recompile and restart the application whenever they occur.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;tsc&lt;/code&gt; command conveniently has a &lt;code&gt;--watch&lt;/code&gt; flag we can use to recompile. Then we can use the &lt;code&gt;nodemon&lt;/code&gt; package to restart the application whenever we detect file changes in the &lt;em&gt;dist&lt;/em&gt; folder (due to the recompilation). Hence we can have the following two scripts:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"build:watch": "tsc --watch",
"run:watch": "nodemon dist/my-app.js --watch dist",
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;But we need these two commands to run at the same time. This can be achieved using the &lt;code&gt;npm-run-all&lt;/code&gt; package.&lt;/p&gt;

&lt;p&gt;Add the required packages as dev-dependencies:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev nodemon npm-run-all
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Final list of scripts:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"build": "tsc",
"run": "node dist/my-app.js",
"build:watch": "tsc --watch",
"run:watch": "nodemon dist/my-app.js --watch dist",
"start": "npm-run-all --parallel build:watch run:watch"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Run &lt;code&gt;npm start&lt;/code&gt; to compile and run the application. Whenever you make a change to a source file, the application will automatically recompile and then restart.&lt;/p&gt;
&lt;h2&gt;
  
  
  Setting up ts-loader for webpack
&lt;/h2&gt;

&lt;p&gt;If your application already has build tooling set up via webpack, the easiest way to add TypeScript support is by using the &lt;code&gt;ts-loader&lt;/code&gt; package.&lt;/p&gt;

&lt;p&gt;This time around, add the &lt;code&gt;ts-loader&lt;/code&gt; and &lt;code&gt;typescript&lt;/code&gt; packages as dev-dependencies:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev ts-loader typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The same &lt;em&gt;tsconfig.json&lt;/em&gt; configuration file as above can be used in this case:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note that in this case, since webpack is already configured to process JavaScript source files, there is no need for including the &lt;code&gt;"allowJs": true&lt;/code&gt; flag here, unless you would like both JavaScript and TypeScript files to be processed by ts-loader. If this is the case, make sure to include the extension &lt;code&gt;js&lt;/code&gt; in the "test" property of the rule added to webpack.config.js below.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;webpack.config.js&lt;/em&gt; add a rule telling webpack to invoke ts-loader for all TypeScript files:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;At this point the application should build and run fine. We are now ready to start converting &lt;em&gt;.js&lt;/em&gt; files to &lt;em&gt;.ts&lt;/em&gt; files.&lt;/p&gt;

&lt;h2&gt;
  
  
  Migrating existing JavaScript files to TypeScript
&lt;/h2&gt;

&lt;p&gt;At this point we should have a tooling setup capable of compiling a combination of JavaScript and TypeScript files. This means we can systematically convert JavaScript files to TypeScript one at a time, compiling and testing the application along the way by renaming a &lt;em&gt;.js&lt;/em&gt; file to &lt;em&gt;.ts&lt;/em&gt; and fixing the compiler errors as they come up. Once all &lt;em&gt;.js&lt;/em&gt; files in the project have been converted, the &lt;code&gt;"allowJs": true&lt;/code&gt; flag in the &lt;em&gt;tsconfig.json&lt;/em&gt; can be removed.&lt;/p&gt;

&lt;p&gt;Here are some general notes to observe during this conversion:&lt;/p&gt;

&lt;h4&gt;
  
  
  use strict
&lt;/h4&gt;

&lt;p&gt;Any &lt;code&gt;'use strict'&lt;/code&gt; directives in existing JavaScript files can be removed since the &lt;code&gt;"strict": true&lt;/code&gt; setting in the tsconfig.json causes &lt;code&gt;'use strict'&lt;/code&gt; to be generated into the compiled JavaScript files automatically.&lt;/p&gt;

&lt;h4&gt;
  
  
  Extending the Error class
&lt;/h4&gt;

&lt;p&gt;If you have defined any sub-classes of &lt;code&gt;Error&lt;/code&gt;, note that there is a &lt;a href="https://github.com/microsoft/TypeScript/issues/13965"&gt;known bug&lt;/a&gt; in TypeScript whereby testing for an instance of this error using &lt;code&gt;instanceof&lt;/code&gt; will not work.&lt;/p&gt;

&lt;p&gt;See this &lt;a href="https://stackoverflow.com/a/48342359/359765"&gt;StackOverflow post&lt;/a&gt; for a work-around. If you have multiple sub-classes of &lt;code&gt;Error&lt;/code&gt;, I would recommend applying the work-around to a common "base" error class (eg. &lt;code&gt;class ErrorBase extends Error&lt;/code&gt;) and have all other error classes extend this class.&lt;/p&gt;

&lt;p&gt;Alternatively, if your code need not support running on IE 11, you should be able to safely change the compiler target from ES5 to ES6 by changing the &lt;code&gt;"target"&lt;/code&gt; property in &lt;em&gt;tsconfig.json&lt;/em&gt; to &lt;code&gt;"es6"&lt;/code&gt; (see the &lt;a href="https://kangax.github.io/compat-table/es6"&gt;ES6 compatibility chart&lt;/a&gt;). This way tsc will generate all classes as actual ES-classes in the target code, effectively circumventing the bug and obviating the need for the work-around.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;There are many benefits to TypeScript that make it worthwhile to take the time to set it up for new projects, and even to convert from JavaScript in existing projects. Making the necessary changes to an existing project's build tooling is generally quite simple, and for new projects there is no need to add a module bundler just to be able to use TypeScript, thanks to tsc.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I have applied this migration to a project from my other articles. Feel free to view the version with the &lt;a href="https://github.com/bhaeussermann/node-js-rest-api/tree/typescript-tsc"&gt;tsc setup&lt;/a&gt; or the version with the &lt;a href="https://github.com/bhaeussermann/node-js-rest-api/tree/typescript-webpack"&gt;webpack / ts-loader setup&lt;/a&gt; on GitHub.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>typescript</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Adding a Swagger UI page to your Express REST API</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Thu, 21 Oct 2021 04:55:38 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/adding-a-swagger-ui-page-to-your-express-rest-api-3cbc</link>
      <guid>https://dev.to/bhaeussermann/adding-a-swagger-ui-page-to-your-express-rest-api-3cbc</guid>
      <description>&lt;p&gt;This article is a continuation of a series about how to build a REST API in Node.js. In the &lt;a href="https://dev.to/bhaeussermann/adding-request-and-response-validation-to-your-express-rest-api-36ia"&gt;preceding article&lt;/a&gt; of this series we added request and response validation that is based on an &lt;a href="https://swagger.io/docs/specification/about/" rel="noopener noreferrer"&gt;OpenAPI&lt;/a&gt; spec of the API. We used the &lt;a href="https://github.com/Surnet/swagger-jsdoc" rel="noopener noreferrer"&gt;swagger-jsdoc&lt;/a&gt; package to generate this OpenAPI spec from comments in our code that annotate the REST operations.&lt;/p&gt;

&lt;p&gt;Consumers of our API won't know how to make requests to it without some form of documentation. The &lt;code&gt;/swagger.json&lt;/code&gt; route which we added returns the OpenAPI spec as a JSON string which serves this purpose. However, this JSON is not very easy to interpret for humans. In this article we will show how the OpenAPI spec can be used to render a &lt;a href="https://swagger.io/tools/swagger-ui/" rel="noopener noreferrer"&gt;Swagger UI&lt;/a&gt; page which serves as a more visual and interactive documentation for our API.&lt;/p&gt;

&lt;p&gt;Add the &lt;a href="https://github.com/scottie1984/swagger-ui-express" rel="noopener noreferrer"&gt;swagger-ui-express&lt;/a&gt; package as a run-time dependency.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

npm install --save swagger-ui-express


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Then in &lt;em&gt;server.js&lt;/em&gt; we register Swagger UI at the route &lt;code&gt;/swagger&lt;/code&gt; just after the statement that registers the &lt;code&gt;/swagger.json&lt;/code&gt; route:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;Loading &lt;code&gt;localhost:3000/swagger&lt;/code&gt; in the browser will now show the Swagger UI page for our API. This will show all endpoints and operations that are available and even allow to try out the calls from the browser!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg2vchnh5z8pwsyuiq7f2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg2vchnh5z8pwsyuiq7f2.png" alt="Screenshot 2021-09-08 at 11-28-29 Swagger UI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While we now have our API spec presented in a nice GUI, consumers of our API may still need access to the OpenAPI JSON definition to import into their client-side tooling. We can add a link to the already-defined &lt;code&gt;/swagger.json&lt;/code&gt; route to the Swagger UI page by changing the previous &lt;code&gt;app.use()&lt;/code&gt; statement to the following:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This will make Swagger UI read the API spec from the specified route and it will display a link to it on the page.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The code for the API developed in this series of articles is available on GitHub &lt;a href="https://github.com/bhaeussermann/node-js-rest-api" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>rest</category>
      <category>openapi</category>
    </item>
    <item>
      <title>Adding request and response validation to your Express REST API</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Wed, 01 Sep 2021 04:51:09 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/adding-request-and-response-validation-to-your-express-rest-api-36ia</link>
      <guid>https://dev.to/bhaeussermann/adding-request-and-response-validation-to-your-express-rest-api-36ia</guid>
      <description>&lt;p&gt;This article is a continuation of a series about how to build a REST API in Node.js. In the &lt;a href="https://dev.to/bhaeussermann/building-a-node-js-rest-api-14o7"&gt;first article&lt;/a&gt; of this series, we created a rudimentary REST API for managing a list of employees. But that API doesn't perform any validation on the requests that are received. Therefore, nothing stops the consumer from making a request with incorrect query parameters or a malformed body. So we could for example send the following request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;POST localhost:3000/employees
{
  "surname": "Symonds",
  "firstname": "Andrew"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The API would happily add the specified object to the list of employees, even though it has the wrong names for the properties ("surname" instead of "lastName" and "firstname" instead of "firstName").&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://github.com/cdimascio/express-openapi-validator"&gt;express-openapi-validator&lt;/a&gt; package addresses this issue by validating requests and responses based on a provided &lt;a href="https://swagger.io/docs/specification/about/"&gt;OpenAPI&lt;/a&gt; spec. Having our responses validated and not just the requests will be a good idea as that will ensure the API code always responds in the expected schema.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;express-openapi-validator&lt;/code&gt; provides a function that takes an OpenAPI specification as a parameter and returns a request handler that we can add to Express. The most straightforward way to use it would be to write our OpenAPI spec in a JSON or YAML file and read it from this file to pass into &lt;code&gt;express-openapi-validator&lt;/code&gt;. But this would mean that whenever we make changes to the API in future, the corresponding part of the OpenAPI spec would have to be updated in this separate file. It would be much easier to keep the OpenAPI spec up to date if it were defined along with the relevant code.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://github.com/Surnet/swagger-jsdoc"&gt;swagger-jsdoc&lt;/a&gt; package enables us to do this. It looks for &lt;a href="https://jsdoc.app/"&gt;JSDoc&lt;/a&gt; comments  in code (annotated with an &lt;code&gt;@openapi&lt;/code&gt; tag) to generate the OpenAPI specification.&lt;/p&gt;

&lt;p&gt;Add the &lt;code&gt;express-openapi-validator&lt;/code&gt; and &lt;code&gt;swagger-jsdoc&lt;/code&gt; packages as run-time dependencies:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save express-openapi-validator swagger-jsdoc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Let's add the JSDoc comments for defining the &lt;code&gt;POST /employees&lt;/code&gt; operation. This involves an &lt;em&gt;employee&lt;/em&gt; structure, which we can define as a schema object on the &lt;code&gt;EmployeesController&lt;/code&gt; class:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;We can then reference this schema object in a comment that we add just before the &lt;code&gt;POST /employees&lt;/code&gt; operation:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We use &lt;code&gt;swaggerJsDoc&lt;/code&gt; to generate the OpenAPI specification by telling which source files to look for the JSDoc comments via the &lt;code&gt;apis&lt;/code&gt; property. We then register the generated OpenAPI spec by passing it into &lt;code&gt;openApiValidator&lt;/code&gt;. We add all of this just before the &lt;code&gt;registerRoutes()&lt;/code&gt; call:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We can also set a route to serve the OpenAPI spec from &lt;code&gt;localhost:3000/swagger.json&lt;/code&gt; as an easy way to access the generated OpenAPI spec. This can help with troubleshooting by ensuring the spec is generated as expected and allows our API consumers to access the spec easily.&lt;/p&gt;

&lt;p&gt;The following statement needs to be added &lt;em&gt;before&lt;/em&gt; the &lt;code&gt;app.use()&lt;/code&gt; call which registers the validation. If it's added after the &lt;code&gt;app.use()&lt;/code&gt; a request to &lt;code&gt;localhost:3000/swagger.json&lt;/code&gt; will be validated and consequently return a 404 response since the &lt;code&gt;/swagger.json&lt;/code&gt; route is not defined in our app's OpenAPI spec.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now, if we make the POST request as above, we get the following 400-code response:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The &lt;a href="https://dev.to/bhaeussermann/adding-a-swagger-ui-page-to-your-express-rest-api-3cbc"&gt;following post&lt;/a&gt; will show how we can leverage the generated OpenAPI spec to add an interactive Swagger documentation page to our API.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The code for the API developed in this series of articles is available on GitHub &lt;a href="https://github.com/bhaeussermann/node-js-rest-api"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>rest</category>
      <category>express</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to implement async operations in your Express REST API</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Mon, 16 Aug 2021 07:37:36 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/exposing-async-operations-through-your-express-rest-api-2hib</link>
      <guid>https://dev.to/bhaeussermann/exposing-async-operations-through-your-express-rest-api-2hib</guid>
      <description>&lt;p&gt;This article is a continuation of a series about how to build a REST API in Node.js. In the &lt;a href="https://dev.to/bhaeussermann/building-a-node-js-rest-api-14o7"&gt;first article&lt;/a&gt; of this series, we built a rudimentary REST API for managing a list of employees. However, instead of using a real database, the &lt;code&gt;EmployeesService&lt;/code&gt; simply maintained the list of employees in memory. Had it implemented actual calls to a database, the methods would likely have been asynchronous, returning promises rather than performing the work synchronously. In this post we will discover how to properly add support for async functions.&lt;/p&gt;

&lt;p&gt;Let's change the &lt;code&gt;EmployeesService.get()&lt;/code&gt; method to be asynchronous and see what happens. By adding the following &lt;code&gt;await&lt;/code&gt; statement we simulate the database query taking 1 second before it returns the results:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now, if we call &lt;code&gt;GET localhost:3000/employees/1&lt;/code&gt; the response we get is the empty object &lt;code&gt;{}&lt;/code&gt;. Keep in mind that in JavaScript an &lt;code&gt;async&lt;/code&gt; method effectively returns a &lt;code&gt;Promise&lt;/code&gt; that resolves when the method completes. It appears that in &lt;em&gt;employees-controller.js&lt;/em&gt; where we call &lt;code&gt;res.json()&lt;/code&gt;...&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Express just &lt;em&gt;stringified&lt;/em&gt; the &lt;code&gt;Promise&lt;/code&gt; object passed into &lt;code&gt;res.json()&lt;/code&gt; rather than awaiting it and using the resolved value. We need to pass the &lt;em&gt;resolved&lt;/em&gt; value into &lt;code&gt;res.json()&lt;/code&gt; instead:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Testing the call using our REST client, this seems to work. However, when we request an employee that doesn't exist, something weird happens. The request hangs and eventually times out. &lt;/p&gt;

&lt;p&gt;This is because the request-handler function passed into the &lt;code&gt;get()&lt;/code&gt; method above is now async. The &lt;code&gt;get()&lt;/code&gt; method handles the case where the passed function throws an error by making the request respond with an error code. Now that the method is async, what happens instead is that the function returns successfully returning a &lt;code&gt;Promise&lt;/code&gt; which eventually gets rejected, and &lt;code&gt;get()&lt;/code&gt; doesn't handle this as expected.&lt;/p&gt;

&lt;p&gt;We can make this route handle errors correctly by using the third &lt;code&gt;next&lt;/code&gt; parameter passed into the request-handler function like so:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Running the request for an employee that doesn't exist now returns the expected response.&lt;/p&gt;

&lt;p&gt;Suppose now that all of our request-handler functions were async (and in a real-world application, most of them will be). We would have to wrap every operation's code into a try-catch block, and pass the error into the &lt;code&gt;next&lt;/code&gt; function to prevent a request hanging forever should an error occur. This is far from ideal. Thankfully, the &lt;a href="https://github.com/Abazhenov/express-async-handler"&gt;express-async-handler&lt;/a&gt; provides a much more convenient way of dealing with errors.&lt;/p&gt;

&lt;p&gt;First, use &lt;code&gt;npm&lt;/code&gt; to add the package as a run-time dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save express-async-handler
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;And use it in &lt;code&gt;EmployeesController&lt;/code&gt; like so:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Of course, if we had not had to deal with the particular case of the 404, then the try-catch block would not have been needed since the &lt;code&gt;asyncHandler()&lt;/code&gt; deals with any errors that might happen.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As long as we remember to pass each async operation's function into &lt;code&gt;asyncHandler()&lt;/code&gt;, we can rest assured that whenever an error occurs within the operation, it will still return the correct error code and message and not just hang until it times out.&lt;/p&gt;

&lt;p&gt;Future posts will show how we can add additional middleware such as for &lt;a href="https://dev.to/bhaeussermann/adding-request-and-response-validation-to-your-express-rest-api-36ia"&gt;adding request / response validation&lt;/a&gt; and &lt;a href="https://dev.to/bhaeussermann/adding-a-swagger-ui-page-to-your-express-rest-api-3cbc"&gt;Swagger documentation&lt;/a&gt; thanks to Node.js packages available for this.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The code for the API developed in this series of articles is available on GitHub &lt;a href="https://github.com/bhaeussermann/node-js-rest-api"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>rest</category>
      <category>express</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building a Node.js REST API</title>
      <dc:creator>Bernhard Häussermann</dc:creator>
      <pubDate>Wed, 04 Aug 2021 05:29:20 +0000</pubDate>
      <link>https://dev.to/bhaeussermann/building-a-node-js-rest-api-14o7</link>
      <guid>https://dev.to/bhaeussermann/building-a-node-js-rest-api-14o7</guid>
      <description>&lt;p&gt;This article is the first of a series outlining the steps to build a REST API from scratch that runs in Node.js using the Express web application framework. In this article, we will show how to set up the project. The following articles will build on this by adding features such as request / response validation and a Swagger UI page for online documentation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project setup
&lt;/h2&gt;

&lt;p&gt;The configuration needed for following along in your own project is minimal. All that is required to get started is a &lt;em&gt;package.json&lt;/em&gt; file generated using &lt;code&gt;npm init&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ensure that &lt;code&gt;"type": "module"&lt;/code&gt; is set within the package.json file. This declares our package as an ES 6 module so we can use &lt;code&gt;import&lt;/code&gt; syntax to import packages in our source code.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Add a basic web server
&lt;/h2&gt;

&lt;p&gt;Add the Express package as a run-time dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Then create a new file &lt;em&gt;server.js&lt;/em&gt; in a folder named &lt;em&gt;src&lt;/em&gt; with the following contents:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;And just like that we have a working web endpoint listening at port 3000!&lt;/p&gt;

&lt;p&gt;In the code above, we have defined a single route which we can use to test that the service is running.&lt;/p&gt;

&lt;p&gt;Testing that our endpoint works is easy as:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run node &lt;code&gt;src/server.js&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Using your favourite REST API testing tool (I recommend &lt;a href="https://www.postman.com/downloads/"&gt;Postman&lt;/a&gt;), request GET &lt;code&gt;localhost:3000/greeting&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We should get a 200-response containing some text as a JSON string.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding automatic restarts
&lt;/h2&gt;

&lt;p&gt;Running our server script as above means that whenever a change is made to a source file, we need to manually stop and start the program for the changes to take effect. This is easy to fix, thanks to a simple tool called &lt;em&gt;nodemon&lt;/em&gt;. We can easily add a script that will restart our application whenever a source file is changed.&lt;/p&gt;

&lt;p&gt;First, we add &lt;em&gt;nodemon&lt;/em&gt; as a development dependency to the project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev nodemon
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;We then define the following set of scripts in &lt;em&gt;package.json&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
  "run": "node src/server.js",
  "run:watch": "nodemon src/server.js --watch src",
  "start": "npm run run:watch"
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The &lt;em&gt;run&lt;/em&gt; script will run the API without automatic restarts as before if we execute &lt;code&gt;npm run run&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;run:watch&lt;/em&gt; script will run the API, restarting it whenever any file inside the &lt;em&gt;src&lt;/em&gt; folder changes.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;start&lt;/em&gt; script will simply run the &lt;em&gt;run:watch&lt;/em&gt; script but can be executed merely as &lt;code&gt;npm start&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Structuring the code based on REST resources
&lt;/h2&gt;

&lt;p&gt;Most REST APIs have their routes arranged based on a number of resources. We will define &lt;em&gt;employees&lt;/em&gt; as a REST resource with CRUD (create, retrieve, update, delete) operations. Keeping with REST conventions, we will define the following routes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;GET &lt;code&gt;/employees&lt;/code&gt;: Return the list of all employees.&lt;/li&gt;
&lt;li&gt;GET &lt;code&gt;/employees/{employee-id}&lt;/code&gt;: Gets the single employee having the ID &lt;code&gt;{employee-id}&lt;/code&gt;. Return a 404 (Not Found) response code if no employee with the specified ID was found.&lt;/li&gt;
&lt;li&gt;POST &lt;code&gt;/employees&lt;/code&gt;: Add a new employee entry.&lt;/li&gt;
&lt;li&gt;PUT &lt;code&gt;/employees/{employee-id}&lt;/code&gt;: Update the details of the employee having the ID &lt;code&gt;{employee-id}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;DELETE &lt;code&gt;/employees/{employee-id}&lt;/code&gt;: Delete the employee having the ID &lt;code&gt;{employee-id}&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we keep on defining all our routes and the code implementing them directly in &lt;em&gt;server.js&lt;/em&gt;, the code will quickly become unmanageable. To help keep the code organized, I recommend defining each REST resource's routes in one file and implementing them in another. We call the file defining the routes the "controller" and the file containing the implementation the "service".&lt;/p&gt;

&lt;p&gt;Implementing the &lt;em&gt;employees&lt;/em&gt; resource leads to the following folder structure:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src
   controllers
      employees-controller.js
   services
      employees-service.js
   server.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here is a simple implementation of &lt;em&gt;employees-service.js&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Whereas in a typical application the objects would be persisted in some kind of a database, we store the list of employees in memory for simplicity's sake.&lt;/em&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;EmployeeNotFoundError&lt;/code&gt; class is defined in a file named &lt;em&gt;employee-not-found-error.js&lt;/em&gt; as:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Note that &lt;code&gt;EmployeesService&lt;/code&gt; does not contain any logic that relates to REST notions like query parameters, response statuses etc. The &lt;code&gt;EmployeesService&lt;/code&gt; is concerned solely with the details of how employees are persisted. This is in adherence to the &lt;a href="https://en.wikipedia.org/wiki/Single-responsibility_principle"&gt;Single-responsibility principle&lt;/a&gt;. It also makes the class easier to test using some testing framework.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;EmployeesController&lt;/code&gt; class deals with the REST-related  specifics and hooks up the REST routes to their respective implementations in the &lt;em&gt;employees&lt;/em&gt; service:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Note the block-comment before the &lt;code&gt;registerRoutes()&lt;/code&gt; method. This is a &lt;a href="https://jsdoc.app/"&gt;JSDoc&lt;/a&gt; comment that specifies descriptions to use when generating documentation using JSDoc. However, in this case, we add the block-comment only to inform our IDE of the expected types of the method's parameters. Visual Studio Code, for instance, has built-in support for JSDoc and will interpret the type-declarations of the &lt;code&gt;app&lt;/code&gt; and &lt;code&gt;controller&lt;/code&gt; parameters inside the block-comment to inform its IntelliSense and code completion functionality.&lt;/p&gt;

&lt;p&gt;We define the &lt;code&gt;ExpressError&lt;/code&gt; class to represent a REST error which is to be handled by a generic error route handler function in &lt;em&gt;server.js&lt;/em&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Finally, we make the following changes to &lt;em&gt;server.js&lt;/em&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;To register the routes, we now simply call &lt;code&gt;registerRoutes()&lt;/code&gt; passing in the Express application and a new instance of &lt;code&gt;EmployeesService&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;We also add a route handler for returning the proper response when an error is thrown.&lt;/li&gt;
&lt;li&gt;To parse the request body of the POST and PUT operations as JSON payloads, we add the statement &lt;code&gt;app.use(express.json())&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We can now use our favourite REST client to test the different routes to verify the behaviour is as expected:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;Get all employees&lt;/em&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET localhost:3000/employees
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;Get employee 1&lt;/em&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET localhost:3000/employees/1
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;Get employee 2 (doesn't exist)&lt;/em&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET localhost:3000/employees/2
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;Update employee 1's first name&lt;/em&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PUT localhost:3000/employees/1
{
  "firstName": "André"
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;Add a new employee&lt;/em&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;POST localhost:3000/employees
{
  "lastName": "King",
  "firstName": "Robert",
  "title": "Sales Representative"
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;Delete employee&lt;/em&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DELETE localhost:3000/employees/2
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  In conclusion
&lt;/h2&gt;

&lt;p&gt;Getting a REST API off the ground using Node.js and Express is relatively straightforward to do, and by defining separate controller and service classes for each type of API resource, we keep the REST-specific details separate from the underlying implementation details of each operation.&lt;/p&gt;

&lt;p&gt;Future posts will show how we can quickly add middleware such as request / response validation and Swagger documentation thanks to Node.js packages that are available for this.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The code for the API developed in this article is available on GitHub &lt;a href="https://github.com/bhaeussermann/node-js-rest-api"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>rest</category>
      <category>express</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
