NestJS: Build integrated project TypeORM, Repository Pattern

Tram Ho


If you have done or read through Laravel, Spring boot, it is not strange to Repository Pattern. There are many articles talking about reasons of use and benefits, so in this article, I will build a demo module using NestJS framework in combination with TypeORM, MySQL.

TypeORM integration

Install dependencies

To integrate TypeORM with Nest:

Integration into the project

To integrate with Nest, we will add the app.module.ts file of the Project

The above options are all basic TypeORM options, you can refer here to learn more and customize

Database migration

With ORM Framework / lib, database migration is an indispensable part, next I will continue to integrate the migration Create ormconfig.ts file.


  1. migrations : Tell TypeORM to know the directory where the migration file is located
  2. cli/migrationsDir : Specify the directory containing the migration file when creating the file with CLI

Add the CLI command

We add 3 scripts to the package.json file:

Migration, Model, Repository

Create the base Service

With projects applying Repository Pattern, we will often have an extra Service class to handle logic related to business. First I will create base Interface Create file i.base.service.ts

In this I will define some commonly used methods, because it is the base, so both the class and the interface I will use Generics

Create the file base.service.ts

BaseService class will implement from BaseService interface, where:

TRepresents Model

Create sample module, model

After the integration and config is complete, we will create a sample module for you


After running, we will add the column to the migration file (at the database / migration directory).

Finally, run the command to migrate any

Create modules

Now we will create more modules users

Create Model

Create the file user.entity.ts

Create UserRepository

After we have a model, we will create the Repository class

Now we need to Extend the Base Repository of TypeORM, and add the Decorator @EntityRepository(User)

Create UserService

The UserService class will extend from BaseService , where the UserRepository and LoggerService will be LoggerService into the constructor via the @Injectable() decorator. In addition to the methods extended from BaseService, I have defined two more methods, findByEmail and getInactiveUsers

User Module and User repository module

After finishing from the Service, Repository, we will create a module so that we can Inject into other Modules, Services, … user.module.ts



At this point we just need to create controller, Inject UserService and use normally user.controller.ts


Above is the brief process of applying Repository Pattern to NestJS project with TypeORM. Code sample, more details can be found here

Share the news now

Source : Viblo