반응형

이 글의 동영상 강좌

https://youtu.be/P9fvgGHd_Jg

Backend의 Nestjs에서 Database(MySQL)를 연결하기 위해 TypeORM을 설정해봅니다.

 

진행 순서는 다음과 같습니다.

MySQL Schema와 User 생성

MySQL Workbench를 이용해서 Schema와 User를 생성합니다.

- Schema : slider

- User : slider

- Password : 1234

자세한 내용은 이전에 작성한 내용을 참조하시기 바랍니다.

https://codegear.tistory.com/32

 

데이터베이스기초-02.MySQL-Schema, User, Table 생성하기

이 글의 동영상 강의입니다. https://youtu.be/hOOiqk8Z1gQ MySQL Workbench를 이용하여 가장 기본적인 Schema와 User를 생성하고, User에게 Schema의 권한을 주는법과, Schema에 Table을 생성하는 법을 알아보겠..

codegear.tistory.com

 

패키지 설치

TypeORM과 MySQL 패키지를 설치합니다.

yarn add @nestjs/typeorm typeorm mysql2

 

TypeORM 설정

/src/orm.config.ts 파일을 아래와 같이 생성합니다.

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

function ormConfig(): TypeOrmModuleOptions {
  const commonConf = {
    SYNCRONIZE: false,
    ENTITIES: [__dirname + '/domain/*.entity{.ts,.js}'],
    MIGRATIONS: [__dirname + '/migrations/**/*{.ts,.js}'],
    MIGRATIONS_RUN: false,
  };

  return {
    name: 'default',
    type: 'mysql',
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT),
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
    logging: true,
    synchronize: commonConf.SYNCRONIZE,
    entities: commonConf.ENTITIES,
    migrations: commonConf.MIGRATIONS,
    migrationsRun: commonConf.MIGRATIONS_RUN,
  };
}

export { ormConfig };

 

Main Module에 typeorm config 설정 추가

/src/app.module.ts에서 @Module -> imports 아래에 다음 내용을 추가합니다.

....
import { TypeOrmModule } from '@nestjs/typeorm';
import { ormConfig } from './orm.config';

@Module({
    imports: [
    	TypeOrmModule.forRootAsync({ useFactory: ormConfig }),
    ]
....

 

환경 설정 파일(.env) 생성

orm.config.ts에서 process.env.DB_NAME과 같은 형태로 환경변수를 참조하도록 했습니다.

/.env 파일을 아래와 같이 생성합니다.(.env는 dotenv라고 읽습니다.)

NODE_ENV=local
DB_HOST=localhost
DB_PORT=3306
DB_USER=slider
DB_PASS=1234
DB_NAME=slider

- local db에 설정한데로 값을 입력하면 됩니다.

 

@nestjs/config 모듈 추가

.env 파일을 사용하기 위해서는 dotenv모듈이 필요합니다.
nestjs에서는 @nestjs/config 모듈을 설치하면 dotenv모듈을 사용할 수 있습니다.

아래와 같이 설치를 합니다.

yarn add @nestjs/config

아래와 같이 main module에 ConfigModule 관련 설정을 추가합니다.

/src/app.module.ts

import { ConfigModule } from '@nestjs/config';
...

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true
    }),
    ....]
...

 

로그 확인

이제 application을 실행해봅니다.

yarn start

application이 정상적으로 실행되면 아래와 같은 로그를 확인할 수 있습니다.

 

Entity 생성

위에서 typeorm 설정 파일의 entity 파일 위치를 아래와 같이 설정했습니다.

ENTITIES: [__dirname + '/domain/*.entity{.ts,.js}'],

따라서 src/domain이라는 폴더를 만들고 entity 파일들을 만들면 됩니다.

 

/src/domain/user.entity.ts 를 아래와 같이 만듭니다.

import { Column, Entity, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import {UserAuthority} from "./user-authority.entity";

@Entity('user', { schema: 'slider' })
export class User {
    @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
    id: number;

    @Column('varchar', { name: 'kakao_id', length: 45 })
    kakaoId: string;

    @Column('varchar', { name: 'email', length: 100 })
    email: string;

    @Column('varchar', { name: 'name', nullable: true, length: 45 })
    name: string | null;

    @Column('varchar', { name: 'gender', length: 10 })
    gender: string;

    @Column('varchar', { name: 'phone', length: 20 })
    phone: string;

    @Column('varchar', { name: 'birth', length: 10 })
    birth: string;

    @Column('varchar', { name: 'profile_image', nullable: true, length: 200 })
    profileImage: string | null;

    @Column('timestamp', {
        name: 'created_at',
        nullable: true,
        default: () => 'CURRENT_TIMESTAMP',
    })
    createdAt: Date | null;

    @Column('timestamp', {
        name: 'updated_at',
        nullable: true,
        default: () => 'CURRENT_TIMESTAMP',
    })
    updatedAt: Date | null;

    @OneToMany(() => UserAuthority, (userAuthority) => userAuthority.user, {
        eager: true,
    })
    authorities?: any[];
}

/src/domain/user-authority.entity.ts를 다음과 같이 만듭니다.

import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './user.entity';

@Entity('user_authority')
export class UserAuthority {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('int', { name: 'user_id' })
  userId: number;

  @Column('varchar',{name: 'authority_name'})
  authorityName: string;

  @ManyToOne(() => User, (user) => user.authorities)
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: User;
}

 

테이블 자동 생성

orm.config.ts 파일에서 syncronize를 true로 변경합니다.

SYNCRONIZE: true,

 

Application을 실행합니다.

yarn start

MySQL에 테이블이 생성된 것을 확인할 수 있습니다.

 

이상으로 TypeORM 설정이 완료되었습니다.

반응형
반응형

Title

이 글의 동영상 강의입니다.

https://youtu.be/hOOiqk8Z1gQ

MySQL Workbench를 이용하여 가장 기본적인 Schema와 User를 생성하고, User에게 Schema의 권한을 주는법과, Schema에 Table을 생성하는 법을 알아보겠습니다.

우선 이전글에서 설치한 MySQL Workbench를 실행합니다.

MySQL Workbench

root 계정으로 접속

  • MySQL Connections 아래 Local instance MySQL의 root 계정으로 설정되어 있는 부분을 클릭하여 MySQL에 접속합니다. 
    Local Instance root connection

Schema 생성

  • 상단 아이콘 중 Database Icon을 클릭합니다. 
    Create Schema Icon
  • Schema 이름을 입력하고, Apply 버튼을 클릭합니다.
    Create Schema Info
  • 생성될 Schema의 review 화면이 나오면 확인 후 Apply 버튼을 클릭합니다.
    Schema Review
  • 다음창에서 Finish 버튼을 클릭합니다.
    Create Schema Appling

User 생성 및 Schema 권한 주기

  • 좌측 메뉴 중 Administration tab에서 "Users and Privileges"를 선택합니다.
    Left Administration Menu 
  • Add Account 버튼을 클릭합니다.
    Users and Privileges
     
  • Login Name과 Password를 입력한 후 상단 tab 메뉴 중 Schema Privileges를 클릭합니다.
    Input Login Name & Password


  • Schema Privileges에서 Add Entry를 클릭합니다.
    Click Add Entry
  • 앞에 생성한 test Schema에만 권한을 주기 위해 "Selected Schema"를 선택하고, 목록 중 "test"를 선택합니다.
    Select Schema
  • 해당 Schema의 전체 권한을 주기 위해 "Select All"을 클릭하고 "Apply"를 선택합니다.
    Click Select All

Connection 만들기

  • 홈화면으로 돌아와 MySQL Connections 옆의 +버튼을 클릭하여 Connection을 새로 만듭니다.
    New Connection
  • Connection 정보를 입력한 후 Test Connection을 클릭하여 확인합니다.
    Setup New Connection
  • 다음창에서 패스워드를 입력합니다.
    Enter password
  • "Successfully"라는 메시지가 나오면 연결에 성공하신것입니다. OK 버튼을 클릭합니다.
    Successfully connection
  • 다시 Setup 화면으로 돌아오면 OK 버튼을 클릭합니다.
    Setup OK
  • Home 화면에 새로운 Connection이 나타납니다. 그 부분을 클릭하여 접속합니다.
    Connection created
  • 왼쪽 메뉴 하단의 Schema tab을 클릭하면 default schema가 test로 나오는 걸 확인할 수 있습니다.
    default schema

테이블 만들기

  • test schema 아래 Tables에서 마우스 오른쪽버튼을 클릭한 후 "Create Table"을 클릭합니다.
    Create Table

다음과 같이 테이블 정보를 입력합니다.
Table Name : user
Column : id(INT), username(VARCHAR(45)), password(VARCHAR(45))
입력 후 "Apply" 버튼을 클릭합니다.

create table

  • Table script를 확인 후 Apply 버튼을 클릭합니다.
    confirm create table script
  • test schema의 tables를 확장하면 생성한 table을 확인할 수 있습니다.
    table list
  • 테이블명 "user"에서 마우스 오른쪽 버튼을 클릭한 후 "Select Rows - Limit 1000"을 클릭합니다.
    Select Rows
  • 다음과 같이 수행된 쿼리와 결과를 확인할 수 있습니다.

query & result

 

이상으로 MySQL에서 Schema 생성, User 생성과 권한 설정, Table 생성을 해 보았습니다.

반응형

+ Recent posts