설치 및 기본사용법

장현욱(Artlogy)·2022년 11월 22일
0

TypeORM

목록 보기
2/5
post-thumbnail

본 포스팅은 공식사이트를 래퍼런스로 포스팅 되었습니다.

설치


패키지

# npm
$ npm i -s typeorm reflect-metadata
# if need to install node typings
$ npm i --save-dev @types/node

# yarn
$ yarn add typeorm reflect-metadata
# if need to install node typings
$ yarn add -d @types/node

간단 설치

# npm
$ npm i -s typeorm

$ yarn
$ yarn add typeorm

데이터베이스

MySQL & MariaDB

$ npm i -s mysql2

$ yarn add mysql2

PostgreSQL & CockroachDB

$ npm i -s pg

$ yarn add pg

SQLite

$ npm i -s sqlite3

$ yarn add sqlite3

Microsoft SQL Server

$ npm i -s mssql

$ yarn add mssql

sql.js

$ npm i -s sql.js

$ yarn add sql.js

Oracle

$ npm i -s oracledb

$ yarn add oracledb

MongoDB

$ npm i -s mongodb@^3.6.0

$ yarn add mongodb@^3.6.0

환경 설정

TypeScript Config

tsconfig.json

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

Database Config

typeorm init

typeorm init으로 data-source.ts파일을 만들거나 직접 만들었을 경우 아래와 같이 설정한다.

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    synchronize: true,
    logging: true,
    entities: [Post, Category],
    subscribers: [],
    migrations: [],
})

Nest.js

NestJS환경에서 Typeorm을 사용 할 경우 다음과 같이 설정한다.

database.config.ts

import { AccountEntities } from '@app/account/account.module';
import { FileEntities } from '@app/file/file.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModuleAsyncOptions } from '@nestjs/typeorm';

export const dataBaseConfig: TypeOrmModuleAsyncOptions = {
  imports: [ConfigModule],
  useFactory: (configService: ConfigService) => ({
    type: 'mariadb',
    host: configService.get<string>('DB_HOST'),
    port: configService.get<number>('DB_PORT'),
    username: configService.get<string>('DB_USER'),
    password: configService.get<string>('DB_PASSWORD'),
    database: configService.get<string>('DB_DATABASE'),
    synchronize: configService.get<boolean>('DB_SYNCHRONIZE'),
    entities: [...AccountEntities, ...FileEntities],
  }),
  inject: [ConfigService],
};

app.module.ts

import { dataBaseConfig } from '@config/database.config';

@Module({
imports[
  ...,
  TypeOrmModule.forRootAsync(dataBaseConfig),
  ...
  ]
})

NestJS는 AOP 디자인 패턴을 위해 설정은 파일을 독립적으로 두는 것이 좋다. (관심사 분리)

기본 사용법


데이터베이스 작업은 테이블 생성에서 시작된다. Typeorm에서는 모델을 통해 테이블 생성을 지시한다. 다음은 Photo 예제 모델이다.

export class Photo{
	id: number;
  	name : string;
  	description : string;
  	views : number;
  	isPublished:boolean;
}

이렇게 하면 모델정의는 끝이다. 허나 이는 ts에서 type을 선언한 것에 불과하기 때문에
실제 데이터베이스에 테이블이 만들어지지 않는다. 실제로 데이터베이스에 테이블을 만들려면
@Entity데코레이터가 필요하다.

@Entity

import { Entity } from "typeorm"

@Entity()
export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}

모델에 @Entity데코레이터를 통해 CRUD가 가능한 테이블이 생성된다.
허나 분명 model안에 요소들을 정의했음에도 column이 존재하지 않을 것이다.
column은 @Column 데코레이터를 통해 생성한다.

@Column

import { Entity, Column } from "typeorm"

@Entity()
export class Photo {
    @Column()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}

데이터베이스 테이블에 열을 추가 할려면 @Column데코레이터를 장식하면된다.

@PrimaryColumn

import { Entity, Column, PrimaryColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}

각 엔티티에는 기본 키 열이 하나 이상 있어야 하며 @PrimaryColumn데코레이터를 사용하면 테이블에 기본키를 추가 할 수 있다.

@PrimaryGeneratedColumn

자동 생성 컬럼은 다음과 같이 설정한다.

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}

@PrimaryColumn대신 @PrimaryGeneratedColumn데코레이터로 변경하면 된다.

Column Data Type

기본적으론 선언된 데이터 타입으로 매핑되지만 다른 데이터 타입으로 매핑하고 싶을 때가 있다. 그때는 다음과 같이 @Column데코레이터에 타입을 지정해준다.

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column({
        length: 100,
    })
    name: string

    @Column("text")
    description: string

    @Column()
    filename: string

    @Column("double")
    views: number

    @Column()
    isPublished: boolean
}

지원되는 모든 @Column 옵션은 여기에서 확인 할 수 있다.

새로 만들기

import "reflect-metadata"
import { DataSource } from "typeorm"
import { Photo } from "./entity/Photo"

const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "root",
    password: "admin",
    database: "test",
    entities: [Photo],	//핵심은 이곳에 데이터베이스에 실제로 만들어질 entities를 등록하는 것이다.
    synchronize: true,
    logging: false,
})

// to initialize initial connection with the database, register all entities
// and "synchronize" database schema, call "initialize()" method of a newly created database
// once in your application bootstrap
AppDataSource.initialize()
    .then(() => {
        // here you can start to work with your database
    })
    .catch((error) => console.log(error))

이 데이터 설정에서 엔터티 목록에 Photo 엔터티를 추가했다.
실 데이터베이스 환경에서 사용 할 각 엔터티가 여기에 나열되어야 한다.

synchronize은 서버를 실행할 때마다 엔터티가 데이터베이스와 동기화되므로 배포환경에선 꺼두는게 좋다.

0개의 댓글