본문 바로가기
프로그래밍/TypeORM

[TypeORM] Working with DataSource

by YuminK 2023. 8. 30.

https://orkhan.gitbook.io/typeorm/docs/data-source

 

What is DataSource
데이터 소스를 설정해야 DB와 소통이 가능하다. 데이터베이스 연결 설정 정보를 가지고 잇고 초기 데이터베이스 연결이나 커넥션 풀 설립을 담당한다.


초기 연결 설립, 커넥션 풀 설립을 위해 initialize 메소드를 호출해야 한다.
destroy 메소드가 불릴 때, 연결이 끊긴다.

일반적으로 어플리케이션 bootstrap에서 initialize 메소드를 호출한다. 
DB와 완전히 처리가 끝난 이후에 destroy를 호출한다. 

예를 들어 백엔드 개발을 하고 있고 서버가 닫히지 않는다면, destroy를 절대 호출되지 않는다. 

Creating a new DataSource
데이타소스 인스턴스를 생성하기 위해서, new DataSource를 부르면서 생성자를 이용해야 한다.
또한 글로벌 변수로 선언하여 어플리케이션 전반에 거쳐 사용할 수 있다.

import { DataSource } from "typeorm"

const AppDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
})

AppDataSource.initialize()
    .then(() => {
        console.log("Data Source has been initialized!")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization", err)
    })

AppDataSource 변수를 export 할 수 있도록 만드는 것은 좋은 생각이다. 
데이터베이스 타입에 따라 의존적인 옵션을 설정할 수 있다.

import { DataSource } from "typeorm"

const MysqlDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [
        // ....
    ],
})

const PostgresDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    entities: [
        // ....
    ],
})

How to use DataSource
일단 데이터 소스를 연결하면, 어디서나 사용할 수 있다.

import { AppDataSource } from "./app-data-source"
import { User } from "../entity/User"

export class UserController {
    @Get("/users")
    getAll() {
        return AppDataSource.manager.find(User)
    }
}

데이터소스 인스턴스를 통해 DB 연산을 처리할 수 있다. 특히 .manager와 .getRepository 속성을 이용하여.

'프로그래밍 > TypeORM' 카테고리의 다른 글

[TypeORM] Entity Inheritance  (0) 2023.08.31
[TypeORM] Embedded Entities  (0) 2023.08.31
[TypeORM] Eager and Lazy Relations  (0) 2023.08.31
[TypeORM] What is EntityManager and Repository  (0) 2023.08.31
[TypeORM] DataSource API  (0) 2023.08.30

댓글