Programming/Node.js

Node.js : NestJS - MySQL 연동하기

파란크리스마스 2024. 8. 8. 02:30
728x90

출처

TypeORM 설치

D:\workspace.nodejs\nestjs_example>npm i --save @nestjs/typeorm typeorm mysql2

src/app.module.ts 내용 - 환경 파일 사용하지 않고 연결하기

내용 추가

import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [

    TypeOrmModule.forRoot({
      /*
      type: 'mysql',
      host: 'localhost',
      port: 8200,
      username: 'bluex',
      password: 'bluex',
      database: 'iloveart',
      */
      type: 'mysql', // process.env.DB_CONNECTION,
      host: process.env.DB_HOST,
      port: +process.env.DB_PORT,
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE,
      
      entities: [],
      synchronize: true,
    }),
  ],

전제 내용

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { configValidationSchema } from 'config/validation/config-validation';
import databaseConfig from '../config/database.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      envFilePath: [ '.env.' + process.env.NODE_ENV ],
      ignoreEnvFile: process.env.NODE_ENV === 'prod',
      //validationSchema: configValidationSchema,
      //load: [ databaseConfig ],
    }),
    TypeOrmModule.forRoot({
      /*
      type: 'mysql',
      host: 'localhost',
      port: 8200,
      username: 'bluex',
      password: 'bluex',
      database: 'iloveart',
      */
      type: 'mysql', // process.env.DB_CONNECTION,
      host: process.env.DB_HOST,
      port: +process.env.DB_PORT,
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE,
      
      entities: [],
      synchronize: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

src/app.module.ts 내용 - 환경 파일 사용

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { configValidationSchema } from 'config/validation/config-validation';
import databaseConfig from '../config/database.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      envFilePath: [ '.env.' + process.env.NODE_ENV ],
      ignoreEnvFile: process.env.NODE_ENV === 'prod',
      validationSchema: configValidationSchema,
      load: [ databaseConfig ],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ ConfigModule ],
      useFactory: (configService: ConfigService) =>
          configService.get('database'),
      inject: [ ConfigService ],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

config/validation/config-validation.ts 내용

import * as Joi from 'joi';

export const configValidationSchema = Joi.object({
  // DATABASE
  DB_CONNECTION: Joi.string().min(1).required(),
  DB_HOST: Joi.string().min(1).required(),
  DB_PORT: Joi.string().min(1).required(),
  DB_DATABASE: Joi.string().min(1).required(),
  DB_USERNAME: Joi.string().min(1).required(),
  DB_PASSWORD: Joi.string().optional(),
});

config/database.config.ts 내용

import { registerAs } from '@nestjs/config';

import { User } from '../src/v1/users/entities/user.entity';

export default registerAs('database', () => {
  return {
    'name': 'default',
    'type': process.env.DB_CONNECTION,
    'host': process.env.DB_HOST,
    'port': process.env.DB_PORT,
    'username': process.env.DB_USERNAME,
    'password': process.env.DB_PASSWORD,
    'database': process.env.DB_DATABASE,
    'entities': [
      // 'dist/**/*.entity{.ts,.js}'
      User
    ],
    'synchronize': false,
    'migrationsTableName': 'migrations_histories',
    'migrationsRun': true,
    'logging': false
    // 'ssl': false,
    // 'extra': {
    //   'ssl': {
    //     'rejectUnauthorized': false
    //   }
    // }
  }
});

src\v1\users\entities\user.entity.ts 내용

import {Column, Entity, PrimaryGeneratedColumn} from 'typeorm';

@Entity({ name: 'users' })
export class User {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public roleId: number;

  @Column()
  public avatarId: number;

  @Column()
  public nickname: string;

  @Column()
  public email: string;

  @Column()
  public phone: string;

  @Column()
  public phoneWithCountryCode: string;

  @Column()
  public bio: string;

}