How to use Nest JS with TypeORM?
Published: 2024-06-04 05:56:41

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
1. **Install Nest CLI**:
   ```bash
   npm install -g @nestjs/cli
   ```

2. **Create a New Project**:
   ```bash
   nest new project-name
   cd project-name
   ```

### Step 2: Install TypeORM and Database Driver
1. **Install TypeORM and the database driver**:
   For MySQL:
   ```bash
   npm install @nestjs/typeorm typeorm mysql2
   ```
   For PostgreSQL:
   ```bash
   npm install @nestjs/typeorm typeorm pg
   ```

### Step 3: Configure TypeORM
1. **Create a `ormconfig.json` File**:
   ```json
   {
     "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
   }
   ```

2. **Configure TypeORM Module in `app.module.ts`**:
   Open `src/app.module.ts` and configure the TypeORM module:
   ```typescript
   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
1. **Generate a User Module**:
   ```bash
   nest g module user
   ```

2. **Generate a User Entity**:
   ```bash
   nest g class user/user.entity --no-spec
   ```

3. **Define the User Entity**:
   Open `src/user/user.entity.ts` and define the entity:
   ```typescript
   import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

   @Entity()
   export class User {
     @PrimaryGeneratedColumn()
     id: number;

     @Column()
     name: string;

     @Column()
     email: string;
   }
   ```

4. **Generate a User Service**:
   ```bash
   nest g service user
   ```

5. **Implement User Service**:
   Open `src/user/user.service.ts` and implement the service methods:
   ```typescript
   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
1. **Generate a User Controller**:
   ```bash
   nest g controller user
   ```

2. **Implement User Controller**:
   Open `src/user/user.controller.ts` and define the controller methods:
   ```typescript
   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
1. **Update `user.module.ts`**:
   Open `src/user/user.module.ts` and configure the module:
   ```typescript
   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
1. **Start the NestJS Application**:
   ```bash
   npm run start:dev
   ```

### Step 8: Test the Application
1. **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.

Disclaimer: This content is generated by AI.