Dependency injection (DI), as a form of inversion of control (IOC), is one of the common software design patterns in object-oriented programming (OOP). DI brings a lot of advantages ranging from higher flexibility, higher reusability to lower dependencies. Undoubtedly, we can apply the DI pattern to our project with Typescript.

There are tons of DI frameworks or libraries out there, for example, InversifyJSTypescript-ioc. Meanwhile, in HK01, we are using Ts.ED for our recent API gateway revamp project as it boosts our development process and provides comprehensive tools. In this article, we will briefly introduce Ts.ED by building a simple API web server.

Project setup

Let’s say we have to create an API server for our clients to get some secret messages. To commence with, we have to set up the project environment by installing dependencies. Ts.ED provides a CLI to start the project:

Image for post

We can also install the dependencies one by one, but please note that all **@tsed**packages must be kept the same version.

Image for post

After initializing the project, we can see there are two files named index.tsand server.tsindex.ts is used to bootstrap our web server. While in server.ts@Configuration() decorator is used to defining our server’s configuration, and $beforeRoutesInit() is used to define express middleware. For example, if we would like to make our root endpoint as /api, we can write the following and our API URL will be like: localhost:3000/api

For more Ts.ED configuration, please check here.

#expressjs #dependency-injection #swagger #typescript #nodejs

Introduction to Ts.ED
3.55 GEEK