영호

[TypeORM] 공식문서로 TypeORM + MySQL설정하기 본문

TypeORM

[TypeORM] 공식문서로 TypeORM + MySQL설정하기

0h0 2022. 5. 9. 22:24
반응형

[TypeORM] 공식문서 보며 TypeORM + MySQL 설정하기

개요

이번 글에서는 공식문서의 Quick start 부분을 따라 하면서 TypeORM의 초기 설정을 해보겠습니다.

순서

  1. cli를 이용해 프로젝트 생성
  2. data-source.ts 수정
  3. data-source.ts대신 ormconfig.json 사용해보기

Installation

  • $ npx typeorm init --name MyProject --database mysql
  • 저는 MySQL을 이용해 MyProject라는 이름의 프로젝트를 생성하겠습니다.**$ typeorm init --name {프로젝트 이름} --database {DB종류}**

프로젝트 구조

├── README.md
├── package-lock.json
├── package.json
├── src
│   ├── data-source.ts
│   ├── entity
│   │   └── User.ts
│   ├── index.ts
│   └── migration
└── tsconfig.json

data-source.ts

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

export const AppDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    synchronize: true,
    logging: false,
    entities: [User],
    migrations: [],
    subscribers: [],
})
  • username, password, database에 본인의 정보를 입력하면 됩니다.
  • entities에는 현재 User.ts만 쓰기 때문에 저렇게 되어 있지만 추후 entity들을 정리하는 폴더의 path를 입력하면 됩니다.
  • 글 아래 ormconfig.json 에서 나옵니다.

index.ts

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

AppDataSource.initialize().then(async () => {

    console.log("Inserting a new user into the database...")
    const user = new User()
    user.firstName = "Timber"
    user.lastName = "Saw"
    user.age = 25
    await AppDataSource.manager.save(user)
    console.log("Saved a new user with id: " + user.id)

    console.log("Loading users from the database...")
    const users = await AppDataSource.manager.find(User)
    console.log("Loaded users: ", users)

    console.log("Here you can setup and run express / fastify / any other framework.")

}).catch(error => console.log(error))

실행

실행결과
실행결과

npm start로 실행을 해봅시다!

  • 정상적으로 동작하는 것을 볼 수 있습니다.
Error: ER_BAD_DB_ERROR: Unknown database 'typeorm_practice'
  • 만약 data-source.ts의 database에 입력한 DB를 생성하는 것을 깜빡하고 실행하게 되면 위와 같은 데이터베이스가 존재하지 않는다는 에러를 만나게 됩니다.****
  • 이 에러는 저희가 data-source.ts의 database에 입력한 DB를 생성해주면 해결됩니다.

ormconfig.json으로 설정해보기

  • 저는 기존 프로젝트에서 ormconfig.json을 통해 설정 정보들을 관리했어서 ormconfig.json 관련해서도 써보겠습니다.
  • TypeORM 설정 관련해서 구글링을 하다 보면 저희가 처음에 입력한 $ npx typeorm init --name MyProject --database mysql 명령어를 통해 자동으로 생성되지만 저는 생성이 안됐습니다...
  • 이 경우 그냥 제가 수동으로 생성을 해주면 됩니다. root위치에 ormconfig.json을 생성해줍니다.
  • 기존의 src/data-source.ts는 삭제하겠습니다.

프로젝트 구조(ormconfig.json)

├── README.md
├── ormconfig.json
├── package-lock.json
├── package.json
├── src
│   ├── entity
│   │   └── User.ts
│   ├── index.ts
│   └── migration
└── tsconfig.json

ormconfig.json

{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "test",
    "password": "test",
    "database": "test",
    "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"
    }
 }
  • 마찬가지로 username, password, database를 채워주면 됩니다.

src/index.ts

import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";

createConnection().then(async connection => {

    console.log("Inserting a new user into the database...");
    const user = new User();
    user.firstName = "Timber";
    user.lastName = "Saw";
    user.age = 25;
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);

    console.log("Loading users from the database...");
    const users = await connection.manager.find(User);
    console.log("Loaded users: ", users);

    console.log("Here you can setup and run express/koa/any other framework.");

}).catch(error => console.log(error));
  • import "reflect-metadata";, import {createConnection} from "typeorm";
  • 기존 index.ts와 비교하면 위 두 개 코드가 추가가 됐습니다..
  • DB 연결 함수를 createConnection를 사용합니다.

실행

실행결과2
실행결과

  • 이번엔 이름을 바꿔서 실행해보겠습니다.
  • daniel 역시 잘 들어간 것을 볼 수 있습니다✌️

마무리

이후 express, typescript, nodemon 등의 설정은 여기를 참고해주세요.

반응형

'TypeORM' 카테고리의 다른 글

[TypeORM] @Transaction 적용  (0) 2022.05.20
[TypeORM] Active-record 패턴  (0) 2022.05.19
[TypeORM] TypeORM entity 작성  (0) 2022.05.14
Comments