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

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...