NestJS is a powerful framework for building efficient, scalable Node.js server-side applications. One of its standout features is its ability to seamlessly integrate with various database solutions, thanks to its modular architecture. Among the many options available, TypeORM stands out as a popular choice for managing data with robust TypeScript support.
In this guide, we’ll walk through how to integrate TypeORM with a NestJS application. By the end, you’ll have a solid understanding of how to set up and configure TypeORM within NestJS, and you’ll be ready to build your own database-driven applications.
Table of Contents
- Setting Up a NestJS Project
- Installing TypeORM and Database Dependencies
- Configuring TypeORM
- Creating Entities
- Defining Repositories
- Using Repositories in Services
- Putting It All Together
1. Setting Up a NestJS Project
First, we need to create a new NestJS project. If you haven’t installed the Nest CLI yet, you can do so with:
npm install -g @nestjs/cli
Now, create a new project:
nest new my-typeorm-app
Navigate to the project directory:
cd my-typeorm-app
2. Installing TypeORM and Database Dependencies
Next, we need to install TypeORM and the database driver of our choice. For this guide, we’ll use PostgreSQL, but TypeORM supports various databases like MySQL, SQLite, etc.
npm install @nestjs/typeorm typeorm pg
3. Configuring TypeORM
With the dependencies installed, we can now configure TypeORM in our NestJS application. Open the app.module.ts
file and set up the TypeORM module:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'test',
password: 'test',
database: 'test',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
In the above configuration, synchronize: true automatically syncs the database schema with your entities on every application launch.
4. Creating Entities
Entities are classes that represent database tables. Let’s create a simple User
entity. First, generate a new module and a service for users:
nest generate module users
nest generate service users
Create the User
entity in a new file src/users/user.entity.ts
:
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
}
Now, import the User
entity in your UsersModule
:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService],
})
export class UsersModule {}
5. Defining Repositories
Repositories are used to interact with the database. NestJS automatically generates a repository for every entity if you use the TypeOrmModule.forFeature
method.
In our UsersService
, we can inject the repository:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
async findAll(): Promise<User[]> {
return this.usersRepository.find();
}
async create(user: User): Promise<User> {
return this.usersRepository.save(user);
}
}
6. Using Repositories in Controllers
Create a controller to expose the users’ endpoints. Use NestJS CLI to generate a controller:
nest generate controller users
Now, implement the controller methods:
import { Controller, Get, Post, Body } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './user.entity';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
async findAll(): Promise<User[]> {
return this.usersService.findAll();
}
@Post()
async create(@Body() user: User): Promise<User> {
return this.usersService.create(user);
}
}
Don’t forget to update your UsersModule
to include the UsersController
:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { User } from './user.entity';
import { UsersController } from './users.controller';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService],
controllers: [UsersController],
})
export class UsersModule {}
7. Putting It All Together
With everything set up, your application should now be functional. You can start your application with:
npm run start
You can test the API by making GET and POST requests to http://localhost:3000/users
.
Here is a brief summary of the files we created and modified:
src/app.module.ts
: Set up TypeORM configuration.src/users/user.entity.ts
: Defined theUser
entity.src/users/users.module.ts
: Set up theUsersModule
.src/users/users.service.ts
: Implemented theUsersService
.src/users/users.controller.ts
: Created theUsersController
.
Conclusion
In this article, we demonstrated how to integrate TypeORM with NestJS, from setting up the project and configuration to creating entities, repositories, and controllers. With this foundation, you’re well-equipped to build and scale your NestJS applications using TypeORM. Happy coding!