# 02. Nestjs with typeorm

개념

* ORM?
    
    * Object Relational Mapping
        
    * 객체와 Relational DB 를 매핑 해주는 기술
        
    * 따라서 자바, 자바스크립트 관계없이 ORM 은 사용 될 수 있으며
        
    * RDB 에 해당하는 MySQL, PostgreSQL, MariaDB, Microsoft SQL Server, Oracle 등이 데이터베이스로 사용 될 수 있다.
        
* TypeORM
    
    * Typescript + ORM
        

장점

* 쿼리문을 사용할 필요없이 기존 방식의 코드 작성 방식으로 작업이 가능
    
* mysql workbench 등에서 작업하는 것 보다 코드의 추적관리가 용이하다
    
    * migration 을 활용하면 상황에 따라서 이전 스키마로 롤백이 가능하다
        

1. 설치
    
    yarn add @nestjs/typeorm typeorm mysql2
    
2. 설정
    
    ormconfig.ts 파일 생성후 세팅
    
    e.g.
    
    ```typescript
    import { TypeOrmModuleOptions } from '@nestjs/typeorm';
    
    const ormConfig: TypeOrmModuleOptions = {
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'local-test',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      migrations: [__dirname + '/migrations/*{.ts,.js}'],
      synchronize: false,
    };
    
    export default ormConfig;
    ```
    
    synchronize: true 를 하면 자동으로 데이터베이스가 갱신된다.
    
    따라서 dev 서버에서는 true 로 두어도 상관 없지만 prod 서버에서는 false 로 설정해두어야 데이터 유실이 발생하지 않는다
    

작업 진척도

* 현재 모종의 이유로 migration:create 는 작동하나 migration:generate 는 작동하지 않는다.
    
* 며칠 방법을 찾아봤지만 진전이 없어 일단은 synchronize:true 로 두고 작업을 진행하기로 했다.
