Say Goodbye to Paid Screen Recording
No Credit Card Required
A free & open source alternative to Loom
3 min to read
Integrating TypeORM with NestJS establishes a sophisticated framework for architecting scalable, database-centric applications.
This discourse meticulously explores the complete implementation cycle, from foundational setup to intricate functionalities, providing an exhaustive roadmap for proficient developers leveraging TypeORM within NestJS.
TypeORM, as a powerful Object-Relational Mapper (ORM), facilitates seamless interaction with relational databases through TypeScript. When coupled with NestJS, it delivers several technical advantages:
npm install -g @nestjs/cli
nest new typeorm-nest-project
cd typeorm-nest-project
For PostgreSQL:
npm install @nestjs/typeorm typeorm pg
For MySQL:
npm install @nestjs/typeorm typeorm mysql2
Create ormconfig.json
:
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "postgres",
"password": "secret",
"database": "nestjs_db",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true
}
Modify app.module.ts
:
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [TypeOrmModule.forRoot()],
})
export class AppModule {}
// user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ unique: true })
email: string;
@Column()
password: string;
}
// post.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
import { User } from './user.entity';
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToOne(() => User, user => user.posts)
author: User;
}
// Augmenting the User entity
import { OneToMany } from 'typeorm';
import { Post } from './post.entity';
@OneToMany(() => Post, post => post.author)
posts: Post[];
// users.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersService } from './users.service';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService],
})
export class UsersModule {}
// users.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>
) {}
async create(userData: CreateUserDto): Promise<User> {
const newUser = this.usersRepository.create(userData);
return this.usersRepository.save(newUser);
}
async findAll(): Promise<User[]> {
return this.usersRepository.find();
}
}
typeorm migration:create -n CreateUsersTable
typeorm migration:run
typeorm migration:revert
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateUsersTable1700000000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255) UNIQUE,
password VARCHAR(255)
)
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE users`);
}
}
class-validator
decorators within DTOs.// DTO with Validation
import { IsEmail, IsString } from 'class-validator';
export class CreateUserDto {
@IsString()
name: string;
@IsEmail()
email: string;
}
The integration of TypeORM with NestJS provides a powerful, structured approach to database management within modern backend applications.
By adhering to best practices, implementing robust entity relationships, and leveraging advanced query optimizations, developers can construct scalable, efficient, and maintainable services.
This guide serves as a foundational reference, equipping engineers with the knowledge to harness the full potential of TypeORM within the NestJS ecosystem.
Need expert guidance? Connect with a top Codersera professional today!