Skip to main content

Node.js app in the real world : what they never really tell you — A 5 part series

Our use case : a REST API written in JavaScript under Node.js with a Mongodb database
I’ll use a Koa server : apart from being very elegant , Koa will allow us to implement only what we really need. We will also use an ODM (Object-Document Mapping), namely Mongoose, because this series do not intend to focus on database management.
Photo by Lachlan Donald on Unsplash
If you prefer Express or Hapi, the native Mongodb driver or even an SQL database, don’t worry too much : most of what I have to say will still hold.
Of course this series I’m introducing here will probably make a few opinionated claims here and there, but I’ll try to keep their number low for one thing, and always provide reasonable arguments. The approach outlined is one among many, but it has been thought out quite a lot and has, I feel, some coherence to it.
This series aims at developers with prior knowledge of some JavaScript, some Node.js and some design patterns, because we’ll cut short sometimes in order to get quickly to the point. Beginners should get the gist of it all though, as it follows common sense rules.
By all means this series is not a full-blown tutorial : there will be gaps for you to fill but hopefully you’ll get on track and have something to think through.
Let’s be ambitious too and try to apply some, yet not all, of the (good in most practical cases) principles of Domain-Driven Design (DDD), namely :
  • domain model where the business logic lives and with zero dependencies (to other librairies as well as to Node.js modules),
  • thin app layer with zero hard dependencies (except of course on the domain) and Dependencies Injection (DI) mechanism,
  • An infrastructure layer containing all the implementation-specific code, notably data access,
  • presentation layer with an HTTPinterface for the API and a Command Line Interface (CLI) app,
  • Extra thin controllers with dependency inversion principle,
  • Overall Separation of Concerns(SoC),
  • Single Responsibilty Principle(SRP) as much as possible,
  • 100% unit test coverage,
  • Dont Repeat Yourself (DRY) code as much as possible,
  • Keep It Simple, Stupid (KISS) principle as much as possible,
  • Aiming at open/closed principlefor classes (I will use mostly classes, more on this later), and more generally getting as close as possible from SOLID code and Inversion of Control (IoC).
But I have chosen not to use the Command Query/Read Segregation(CQRS) which is interesting but in a lot of practical cases (including our own here) overcomplicated. You’ll see throughout the series that while following a constrained architecture is obviously worthwhile in the long run, I’ll have no hesitation to deviate from the canon for practical reasons, or simply to avoid overkill.
I will define or provide quick summary of all the principles mentioned above in the various parts of the series, as our use case will unfold.
A visual representation of a highly decoupled software architecture. As stated on the picture itself, we’ll use in this series only what we (practically) need. Courtesy of Herberto Graca
All of this is certainly not trivial but very much worth doing, and it requires good planification.
In our 5 part series we will dive into the practical questions that you will face doing so. See below.
Why choosing DDD you’ll ask ? Well certainly DDD certainly means more code but adds lots of benefits that makes it more than worth : what if you want to change your database or even your ODM ? what if you want to change your server framework or even rewrite your app in another language, or package parts of it only ? DDD will allow this through the power of decoupling.
Decoupling is highly powerful indeed. In the approach I’ll take, I’ll be using dependency injection, meaning we will not rely on concrete implementation (only the infrastructure and presentation layers have dependencies). This means easy dependency swapping and vastly facilitates unit testing and code coverage. Code is more readable too.
In the app layer, you’ll see code like the one below. Concrete implementation of the remove() method is hidden :
Oh by the way, in all our code snippets, we’ll omit (except in a few edge cases) the export statements, but don’t forget to add them in your own code.
I’ll be using mostly classes, as stated above, instead of (factory) functions. I’ll not enter a debate here on whether Object Oriented Programming (OOP) or Functional Programming are better/more suited. You’ll find lots of articles on this subject, like this one. It really does not matter much for the architecture I’ll be presenting if we choose one or the other.
Though I know classes were somehow forcibly added into the JavaScript language, I’ll still use them for two main reasons : they feel elegant to me (I really care about readibility as you might have already guessed), and they might be easier to port to other languages. But again, using a functional approach would be fine too.
Part 1 is about :
  • How to organize code, name files and write simple, readable, intuitive code, under good coding guidelines ?
  • How to minimize dependencies by implementing a service container for dependency injection ?
  • When and how to use events ?
Part 2 is about :
  • How to implement the repository pattern (we hinted this already), separate domain classes from database models and add some automated persistence logic in accordance with the domain ?
  • How to set up your HTTP server ?
  • How to handle routing and manage controllers ?
Part 3 is about :
  • How to manage authentication ?
  • How to manage access control ?
  • How to handle errors properly ?
Part 4 is about :
  • How to comment code and create useful documentation ?
  • How to aim at 100% unit test coverage ?
  • How to use some CLI commands consuming your app services ?
Part 5 is about :
  • How to deploy in production ?
  • How to implement useful decorators ?
  • How to go beyond infinity ?
Stay tuned for Part 1 !
PS / One small disclaimer in case you haven’t noticed : English is not my native language, so I do apologize for any mistake I’ll be making (or have already made).

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...