TypeORM은 Node.js, 브라우저, 리액트 네이티브 등에서 실행되는 ORM이다. 타입스크립트와 자바스크립트로 TypeORM을 사용할 수 있다.
TypeORM은 Active Record와 Data Mapper 패턴을 모두 지원해서, 고품질의, 느슨하게 결합된(loosely coupled), 확장 가능한, 유지 보수 가능한 애플리케이션을 생산성 높게 작성할 수 있다.
TypeORM의 공식문서에서 제공하는 스텝바이스텝 가이드 중에서 모델 생성하기, Entity 생성하기, 테이블 칼럼 추가하기, Primary 칼럼 생성하기, 자동생성 칼럼 생성하기, 칼럼 데이터 타입, 새로운 DataSource 생성하기에 대해 공부하였다.
모델은 데이터베이스의 테이블이다.
모델을 사용한다.아래와 같이 Photo 모델을 생성한다.
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}
Entitiy는 @Entity 데코레이터가 붙여진 모델이다.
아래와 같이 Photo 모델을 Entity로 만든다.
import { Entity } from "typeorm"
@Entity()
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}
이제 Photo entity를 사용해 데이터베이스를 생성할 수 있고 애플리케이션 어디서든지 이 entity를 사용할 수 있다.
칼럼으로 만들고 싶은 entity 프로퍼티에 @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
}
Photo 테이블에 id, name, description, filename, view, isPublished 칼럼이 추가되었다.number는 integer로,string은 varchar로,boolean은 bool로칼럼을 Primary 키로 만들려면 @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
}
@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
}
varchar나 integer로 칼럼의 데이터 타입을 제한하지 않도록 칼럼의 데이터 타입을 수정할 수 있다.
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
}
Entity를 생성하고, DataSource를 설정한다.
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],
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))
type 에는 사용 중인 데이터베이스 종류를 입력한다.entities 에는 데이터 소스로 사용하기 위한 entity 목록으로 Photo entity를 추가하였다. 각각의 entity는 반드시 이곳에 나열해야 한다.synchronize 설정은 애플리케이션을 실행할 때마다 entity가 데이터베이스와 동기화되도록 한다.