If you’re building scalable and maintainable applications with NestJS, integrating a powerful ORM like TypeORM is a game-changer for handling database interactions. In this article, we’ll explore how to set up and use TypeORM in a NestJS project, complete with practical examples.
What is TypeORM?
TypeORM is an Object-Relational Mapping (ORM) tool that allows developers to interact with databases using TypeScript classes. It simplifies data management by mapping database tables to JavaScript objects, making database queries more intuitive and maintainable.
Why Use TypeORM with NestJS?
- Seamless Integration: NestJS supports TypeORM out of the box with the @nestjs/typeorm package.
- TypeScript Support: Leverage TypeScript’s type safety and annotations to define database entities.
- Declarative Relationships: Easily define relationships like one-to-many, many-to-many, etc.
- Migrations: Manage schema changes efficiently.
Getting Started: Setting Up TypeORM in a NestJS Project
1. Install Dependencies
First, add the necessary packages to your NestJS project:
npm install @nestjs/typeorm typeorm mysql2
Replace mysql2 with the driver of your choice (pg for PostgreSQL, sqlite3 for SQLite, etc.).
2. Configure the Database Connection
Update your AppModule to include TypeORM configuration:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql', // ('postgres') or your preferred database type
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'nestdb',
entities: [__dirname + '../../**/**/*entity{.ts,.js}'],
autoLoadEntities: true, // Automatically load entities
synchronize: true, // Disable this in production
}),
],
})
export class AppModule {}
3. Define an Entity
Create an entity folder and define an entity, which maps to a database table.
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ unique: true })
email: string;
@Column()
password: string;
}
4. Create a Service and Repository
Inject the Repository to interact with the database.
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async create(user: Partial<User>): Promise<User> {
const newUser = this.userRepository.create(user);
return this.userRepository.save(newUser);
}
}
5. Build a Controller
Create endpoints to manage user data.
import { Controller, Get, Post, Body } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
async getAllUsers(): Promise<User[]> {
return this.userService.findAll();
}
@Post()
async createUser(@Body() user: Partial<User>): Promise<User> {
return this.userService.create(user);
}
}
6. Add the Module
Finally, bring everything together in a UserModule.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UserService } from './user.service';
import { UserController } from './user.controller';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
Register the UserModule in your AppModule:
@Module({
imports: [
TypeOrmModule.forRoot({...}),
UserModule,
],
})
export class AppModule {}
Advanced Features
1. Defining Relationships
Create relationships between entities, such as OneToMany or ManyToOne:
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToOne(() => User, (user) => user.posts)
user: User;
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Post, (post) => post.user)
posts: Post[];
}
2. Using QueryBuilder
For complex queries, use TypeORM's QueryBuilder:
async getUsersWithPosts(): Promise<User[]> {
return this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.posts', 'post')
.getMany();
}
3. Managing Migrations
Generate and run migrations for schema updates:
npm run typeorm migration:generate -- -n AddNewField
npm run typeorm migration:run
For a complete guide for Migrations please read this article: Database Migrations with TypeORM in NestJS
Conclusion
Integrating TypeORM with NestJS simplifies database interactions while keeping your code clean and scalable. Whether you're working on a small project or an enterprise-grade application, this duo provides everything you need for robust data management.
Feel free to share your experiences or ask questions in the comments. Let’s build something amazing together! π
Happy Learning π
Follow Me:
#NestJS #TypeORM #WebDevelopment #NodeJS #TypeScript #FullStackDevelopment #Programming #SoftwareEngineering #CodingTips #Tech
No comments:
Post a Comment