Nest.js TypeOrm으로 데이터베이스(Postgres) 연결하기

에옹이다아옹·2023년 10월 27일
1
post-thumbnail

TypeOrm?

node.js에서 실행되고 typeScript로 작성된 객체 관계형 매퍼 라이브러리

MySQL, PostgreSQL, MariaDB, SQLite,MS SQL Server, ORACLE, SAP Hana 및 WebSql과 같은 여러 데이터베이스를 지원


내가 사용하고자 했던 데이터베이스는 postgres라서

npm install pg psql typeorm @nestjs/typeorm --save

다음 명령어를 입력해 설치하였다

이미 postgres 데이터베이스 생성까지 완료했다는 전제하에 설명을 이어나가겠다.

우선 데이터베이스를 연결해야 할 것 같아서 src 폴더 밑에 config 폴더를 만들어 typeorm.config.ts 파일을 생성했다

export const typeormConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: ${postgres 설치할 때 설정한 비밀번호},
  database: ${생성한 데이터베이스 이름},
  entities: [User],
  // entities: [__dirname + '../**/*.entity.{js, ts}'],
  synchronize: true, //false로 해놓다가 필요할 때 true로 바꾸기!
};

synchronize 옵션을 쓸 때는 주의해야할 점이 entity와 database간의 씽크를 맞춰줘서 해당 기능을 사용하면 편할 수 있지만❗️
원하지 않는 시점에 database구조가 달라질 수 있으므로 주의해야한다
entity 설정과 씽크를 맞춰주기 위해서 typeorm cli 를 이용해서 원하는 시점에 sync를 맞추는게 👍🏻

그 후에 서버를 실행해줬더니

컬럼이 원하는대로 생성되었다!
👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻👏🏻


User Entity 생성

그 다음 src 폴더 밑에 entity 폴더를 만들어 user.entity.ts를 생성했다

내가 설계한 user 데이터베이스는 다음과 같다

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

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

  @Column({ unique: true })
  userId: string;

  @Column()
  name: string;

  @Column({ unique: true })
  nickName: string;

  @Column({ unique: true })
  email: string;

  @Column()
  password: string;
}

PrimaryGeneratedColumn()은 Jpa에서 GeneratedValue(strategy = GenerationType.IDENTITY)와 같다고 보면 될 듯

unique 설정을 하고 싶다면 Column 데코레이터에 {unique:true}를 주면 된다


App.moduel.ts 파일 수정

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeormConfig } from './config/typeorm.config';
import { ConfigModule } from '@nestjs/config';
import * as process from 'process';


@Module({
  imports: [
    TypeOrmModule.forRoot(typeormConfig),
    ...
})
export class AppModule {}

마지막으로 TypeOrmModule.forRoot()로 앞서 만들어두었던 typeormConfig를 넣어주면 된다!

profile
숲(구조)을 보는 개발자

0개의 댓글