Effortlessly Integrate TypeORM with NestJS: A Step-By-Step Guide
Uncover the power of TypeORM and NestJS integration for effective database management. Explore, step-by-step, modern techniques to streamline your development process. Throughout this article, you'll learn how to set up a new NestJS project, configure the TypeORM module, create a new entity, and interact with the data using repositories. The target audience for this tutorial is web developers familiar with TypeScript and looking to develop scalable applications with TypeORM and NestJS.
Prerequisiteslink
To follow along with this tutorial, make sure you meet the following requirements:
- Have Node.js (version 14.x or higher) installed
- Have a working knowledge of TypeScript
- Familiarity with object-relational mapping (ORM)
Setting Up the Projectlink
Start by installing the NestJS CLI using the following command:
npm i -g @nestjs/cli
Next, create a new NestJS project using the NestJS CLI by running:
nest new your_project_name
Replace your_project_name
with the desired name for your project. Navigate to the project directory:
cd your_project_name
Installing TypeORM and Dependencieslink
Now, install TypeORM and its required dependencies using the following command:
npm install --save @nestjs/typeorm typeorm pg
In this example, we'll use PostgreSQL as our database. Replace pg
with the appropriate npm package if you prefer another database, such as mysql
or sqlite3
.
Configuring TypeORM within NestJSlink
Create a new file named ormconfig.json
in the root of your project directory. This file will store the configuration for TypeORM. Add the following properties to configure the connection to the PostgreSQL database:
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "your_db_username",
"password": "your_db_password",
"database": "your_db_name",
"entities": ["dist/**/*.entity.js"],
"synchronize": true
}
Replace your_db_username
, your_db_password
, and your_db_name
with your database credentials.
Next, import the TypeOrmModule
from @nestjs/typeorm
in app.module.ts
.
import { TypeOrmModule } from '@nestjs/typeorm';
Include the TypeOrmModule
in the imports
array of the @Module
decorator and use the forRoot()
method to load the ORM configuration:
imports: [TypeOrmModule.forRoot()]
Your app.module.ts
should now look like this:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [TypeOrmModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Creating an Entitylink
An Entity is a TypeScript class mapped to a database table. In this example, we'll be creating a simple User
entity. Create a new folder called entities
inside the src
folder, and then create a new file named user.entity.ts
. Add the following content to that file:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
email: string;
@Column()
name: string;
}
Creating a Repositorylink
A Repository is a class that interacts with your entity and performs the necessary CRUD operations. In this article, we will create a repository for the User
entity.
First, create a new folder named users
inside the src
folder. Now create a file named users.repository.ts
and add the following code:
import { EntityRepository, Repository } from 'typeorm';
import { User } from '../entities/user.entity';
@EntityRepository(User)
export class UsersRepository extends Repository<User> {}
Integrating the Repository in a Servicelink
Now, let's create a UsersService
that will use the UsersRepository
to handle the CRUD operations for the User
entity. Create a new file named users.service.ts
in the users
folder:
import { Injectable } from '@nestjs/common';
import { UsersRepository } from './users.repository';
import { User } from '../entities/user.entity';
@Injectable()
export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
async findAll(): Promise<User[]> {
return await this.usersRepository.find();
}
}
And finally, import both the UsersService
and UsersRepository
in app.module.ts
.
import { UsersRepository } from './users/users.repository';
import { UsersService } from './users/users.service';
Add them to the providers
array in the @Module
decorator as well:
providers: [AppService, UsersService, UsersRepository]
You have successfully integrated TypeORM with NestJS, set up a connection to a PostgreSQL database, created an entity, and used a repository to interact with the Entity.
Now you can extend your application further by implementing different functionalities of your choice using TypeORM and NestJS. For additional information on TypeORM and NestJS, significant resources can be found in the TypeORM documentation and the official NestJS documentation.