[UniLetter] TypeORM 설치 및 MySQL연결

Seohyun-kim·2022년 1월 5일
0
post-thumbnail

Typescript로 코드를 작성할 계획인데,
DB와 연결할 ORM 중에 TypeORM과 조합이 괜찮다고 해서 설치해보고자 한다.

1. TypeORM 설치

npm 으로 전역에 설치

$ npm i -g typeorm

기본 typeORM mysql 프로젝트 생성

$ typeorm init --database mysql

2. Local 에 DB 생성

$ CREATE DATABASE inu_events default CHARACTER SET UTF8;

3. ormconfig.json 수정

{
   "type": "mysql",
   "host": "localhost",
   "port": 3306,
   "username": "root",
   "password": "",
   "database": "inu_events",
   "synchronize": true,
   "logging": false,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}

4. 실행 (데이터베이스 연결 테스트)

MySQL [inu_events]> show tables;
+----------------------+
| Tables_in_inu_events |
+----------------------+
| user                 |
+----------------------+
1 row in set (0.003 sec)

MySQL [inu_events]> SELECT * FROM user;
+----+-----------+----------+-----+
| id | firstName | lastName | age |
+----+-----------+----------+-----+
|  1 | Timber    | Saw      |  25 |
+----+-----------+----------+-----+
1 row in set (0.001 sec)

5. dotenv 사용하여 환경변수 설정

5.1 .env 파일 생성

반드시 최상위 폴더에 생성.
.env

DB_PW = "내 비번"

5.2 ormconfig.ts 작성

ormconfig.ts

export default {
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: process.env.DB_PW,
    database: 'inu_events',
    synchronize: true,
    logging: false,
    "entities": [
        "src/entity/**/*.ts"
    ],
    "migrations": [
        "src/migration/**/*.ts"
    ],
    "subscribers": [
        "src/subscriber/**/*.ts"
    ],
    "cli": {
        "entitiesDir": "src/entity",
        "migrationsDir": "src/migrations",
        "subscribersDir": "src/subscriber"
    }
};

5.3 .gitignore에 추가

내 정보가 git에 올라가면 안되니까아

.gitignore

.env

0개의 댓글