Using NestJS with TypeORM is a common setup for building scalable applications. Here’s a step-by-step guide on how to integrate TypeORM into a NestJS project:
Step 1: Set Up a New NestJS Project
- Install Nest CLI:
npm install -g @nestjs/cli
- Create a New Project:
nest new project-name
cd project-name
Step 2: Install TypeORM and Database Driver
- Install TypeORM and the database driver: For MySQL:
npm install @nestjs/typeorm typeorm mysql2
For PostgreSQL:
npm install @nestjs/typeorm typeorm pg
Step 3: Configure TypeORM
-
Create a
ormconfig.json
File:
{
"type": "mysql", // or 'postgres'
"host": "localhost",
"port": 3306, // or 5432 for PostgreSQL
"username": "root", // or your PostgreSQL username
"password": "password", // or your PostgreSQL password
"database": "test",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true
}
-
Configure TypeORM Module in
app.module.ts
: Opensrc/app.module.ts
and configure the TypeORM module:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
@Module({
imports: [
TypeOrmModule.forRoot(),
UserModule,
],
})
export class AppModule {}
Step 4: Create a User Module, Entity, and Service
- Generate a User Module:
nest g module user
- Generate a User Entity:
nest g class user/user.entity --no-spec
-
Define the User Entity:
Open
src/user/user.entity.ts
and define the entity:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
}
- Generate a User Service:
nest g service user
-
Implement User Service:
Open
src/user/user.service.ts
and implement the service methods:
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 usersRepository: Repository<User>,
) {}
findAll(): Promise<User[]> {
return this.usersRepository.find();
}
findOne(id: number): Promise<User> {
return this.usersRepository.findOneBy({ id });
}
async remove(id: number): Promise<void> {
await this.usersRepository.delete(id);
}
create(user: Partial<User>): Promise<User> {
const newUser = this.usersRepository.create(user);
return this.usersRepository.save(newUser);
}
}
Step 5: Create a User Controller
- Generate a User Controller:
nest g controller user
-
Implement User Controller:
Open
src/user/user.controller.ts
and define the controller methods:
import { Controller, Get, Post, Delete, Param, 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()
findAll(): Promise<User[]> {
return this.userService.findAll();
}
@Get(':id')
findOne(@Param('id') id: number): Promise<User> {
return this.userService.findOne(id);
}
@Post()
create(@Body() user: Partial<User>): Promise<User> {
return this.userService.create(user);
}
@Delete(':id')
remove(@Param('id') id: number): Promise<void> {
return this.userService.remove(id);
}
}
Step 6: Integrate User Module into App Module
-
Update
user.module.ts
: Opensrc/user/user.module.ts
and configure the module:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService],
controllers: [UserController],
})
export class UserModule {}
Step 7: Run the Application
- Start the NestJS Application:
npm run start:dev
Step 8: Test the Application
-
Test Endpoints:
Use a tool like Postman or curl to test the RESTful API endpoints:
-
GET /users
: Retrieve all users. -
GET /users/:id
: Retrieve a user by ID. -
POST /users
: Create a new user. -
DELETE /users/:id
: Delete a user by ID.
-
This guide provides a foundational approach to integrating TypeORM into a NestJS application. You can further expand and customize it based on your application's requirements.
Support My Work ❤️
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me 🌍
Let’s stay connected! You can follow me or reach out on these platforms:
🔹 YouTube – Tutorials, insights & tech content
🔹 LinkedIn – Professional updates & networking
🔹 GitHub – My open-source projects & contributions
🔹 Instagram – Behind-the-scenes & personal updates
🔹 X (formerly Twitter) – Quick thoughts & tech discussions
I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)