Setup Node.js Express application with Typescript, Router Controller, TypeDI and TypeORM - Part 1

Javascript today is everywhere from front-end to back-end and it is very easy to build a simple RESTful API but, if you are like me and you are not at ease building complex systems without static type checking, surely you will have discarded this option.

This post will not cover what node.js is. There are an infinite number of posts where it is described what node.js is. As the official site says:

Node.js is an asynchronous event driven JavaScript runtime, designed to build scalable network applications.

Why use Node.js ?

These are some of the advantages of using node.js:

  • Javascript as fullstack language: you can use the same language from front-end to back-end
  • Speed: node.js uses Chrome's V8 engine which is used in the Chrome browser to compile functions written in JavaScript into machine code
  • Non-blocking Input/Output and asynchronous request handling
  • Lightweight and small footprint: an advantage for the microservices architecture that allows orchestrators to create new service instances when requests increase
  • A huge ecosystem of libraries for every type of scenario thanks to npm

Some of the advantages listed above can also be seen as disadvantages:

  • Javascript is an interpreted, dynamic typing, prototype-based programming language. If you are comfortable with static typing object oriented languages like Java or C# you could be a little disoriented.
  • Asynchronous programming model which is more difficult in comparison to the linear blocking I/O programming
  • Performance bottlenecks on CPU intensive operation
  • Callback hell: like the homonymous site reports

    Asynchronous JavaScript, or JavaScript that uses callbacks, is hard to get right intuitively.

How can we get around these obstacles?

  • Typescript : is a typed superset of JavaScript that compiles to plain JavaScript. So you have a full object oriented, static typing language as Java or C#

  • Async/Await: which simplify nested callbacks

  • Dependency Injection: use libraries like TypeDI or InversifyJS to inject services into your code

  • Routing Controllers: use libraries like routing-controllers to bind requests to methods of classes acting as controllers instead of inline plain functions

  • ORM: using libraries like TypeORM you will be able to write queries using the object-oriented paradigm of your programming language

This is enough to continue our journey on part 2 that will allow us to move from a RESTful API service written in plain Javascript using Express framework to a version written in TypeScript with the aid of Routing Controllers, end-points defined by by annotations, dependency injection of services using TypeDI and use of an ORM using TypeORM.