본문 바로가기
NestJS

[NestJS] NestJS DB연결하기

by 깅민 2025. 5. 28.

1. DB연결

NestJS와 PostgreSQL 과 연결하는 걸 해보겠습니다.

 

설치

npm i @nestjs/typeorm typeorm pg

 

pg: PostgreSQL 드라이버

@nestjs/typeorm: Nest용 TypeORM 모듈

typeorm: ORM 자체

 

2. AppModule에 TypeORM 연결 설정 추가

import { Module } from '@nestjs/common';
import { TypeOrmModule } from "@nestjs/typeorm";
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: "postgres",
      host: "localhost",
      port: 5432,
      username: "test",
      password: "test",
      database: "test_db",
      entities: [__dirname + `/**/*.entity{.ts,.js}`],
      synchronize: false // 개발환경에서만 true, 배포시 false
    }),
    UserModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

 

2-1. entities

entities: [__dirname + '/**/*.entity{.ts,.js}']

TypeORM이 DB테이블로 변환할 클래스(Entity) 파일들을 어디서 찾을지 알려주는 설정

 

__dirname 은 현재 파일의 디렉토리 경로를 의미하고,

/**/*.entity{.ts,.js} 는 모든 하위 폴더에서 *.entity.ts 또는 *.entity.js 파일 찾기

 

예를 들어 @Entity() 데코레이터가 붙은 클래스를 자동으로 찾아서 DB테이블로 생성합니다.

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

  @Column()
  name: string;
}
  • @Entity() 데코레이터가 붙은 클래스를 TypeORM이 감지
  • @Column() 들을 읽고 DB 컬럼 스펙을 분석
  • synchronize: true 이면 앱 실행 시 DB에 테이블이 없으면 생성하거나, 차이가 있으면 자동 수정
  • User라는 클래스는 user 테이블로 변환됨 (기본적으로 클래스 이름을 소문자로 바꿈)

 

이렇게 클래스만 만들어도 아래와 같은 SQL이 자동으로 실행됩니다. ( synchronize: true일 때 )

CREATE TABLE user (
  id SERIAL PRIMARY KEY,
  name VARCHAR,
  age INT
);

 

2-2. synchronize

이 설정은 앱을 실행할 때 자동으로 DB 테이블을 동기화합니다.

 

저는 SQL로 조작할거기 때문에 false로 하겠습니다.

 

3. 엔티티 생성

// src/user/user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: "user", schema: "test_schema" })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  age: number;

  @Column()
  gender: string;

  @Column()
  phone: string;
}

 

4. 엔티티 모듈에 등록

// src/user/user.module.ts

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])],
  providers: [UserService],
  controllers: [UserController],
})
export class UserModule {}

 

TypeOrmModule.forFeature([...])는 현재 모듈(UserModule)에서 특정 엔티티(User)를 TypeORM이 사용할 수 있게 설정합니다.

즉, UserRepository 또는 @InjectRepository(User)를 이 모듈에서 사용할 수 있도록 등록합니다.

 

"이 모듈(UserModule)은 User라는 Entity에 대한 TypeORM 기능을 사용할 준비가 되어 있다."

 

5. Service

// src/user/user.service.ts
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 readonly userRepository: Repository<User>,
  ) {}

  async findAll(): Promise<User[]> {
    return this.userRepository.find(); // select * from user
  }
}

 

6. Controller

import { Controller, Get } 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 getUsers(): Promise<User[]> {
    return this.userService.findAll();
  }
}

 

7. 결과

데이터를 잘 가져오는 걸 확인할 수 있습니다.

'NestJS' 카테고리의 다른 글

[NestJS] NestJS WSL 배포하기  (0) 2025.05.29
[NestJS] NestJS CORS  (0) 2025.05.29
[NestJS] NestJS 시작하기  (1) 2025.05.28