Programming/Node.js

Node.js : NestJS 데이터베이스 연동하기 (MySql, TypeORM)

파란크리스마스 2024. 8. 10. 15:45
728x90

출처

Entity 객체

Entity 부모 클래스 ( node_modules\typeorm\decorator\entity\Entity.d.ts )

import { EntityOptions } from "../options/EntityOptions";
/**
 * This decorator is used to mark classes that will be an entity (table or document depend on database type).
 * Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
 */
export declare function Entity(options?: EntityOptions): ClassDecorator;
/**
 * This decorator is used to mark classes that will be an entity (table or document depend on database type).
 * Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
 */
export declare function Entity(name?: string, options?: EntityOptions): ClassDecorator;

User 클래스 ( entities/user.entity.ts )

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

@Entity({ name: 'users' })
export class User extends BaseEntity {
  @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;

}

Service 클래스 ( user.service.ts )

Controller에서 요청 받은 내용을 Service 객체를 통해서 데이터 저장 및 검색한 결과를 반환

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

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

@Injectable()
export class UsersService {

  constructor(
    @InjectRepository(User)
    private readonly _usersRepository: Repository<User>,
  ) { }

  public async detailUser(id: number): Promise<any> {
    const queryBuilder = this._usersRepository.createQueryBuilder('users');
    queryBuilder.where('users.id = :userId', { userId: id });
    const user = await queryBuilder.getOne();
    return user;
  }
}

Controller 클래스 ( user.controller.ts )

Controller는 http 요청을 처리 하고 클라이언트에 응답을 반환하는 하는 클래스

import { Controller, Get, Param } from '@nestjs/common';
import { User } from './entities/user.entity';
import { UsersService } from './user.service';

@Controller()
export class UsersController {
  constructor(
    private readonly _userService: UsersService
  ) { }

  @Get('detail/:id')
  public async findOne(@Param('id') id : number) {
    return this._userService.detailUser(id);
  }

}

Module 클래스 ( user.module.ts )

Module 데코레이터가 붙어있는 클래스로 Nest가 전체 어플리케이션의 구조를 정의한 메타데이터 제공

  • providers : Service 클래스
  • controllers : Controller 클래스
  • imports : 
  • exports : 
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './user.controller';
import { User } from './entities/user.entity';
import { UsersService } from './user.service';

@Module({
  imports: [ TypeOrmModule.forFeature([ User ]), ],
  controllers: [ UsersController ],
  providers: [ UsersService ],
})
export class UsersModule {
}

메인 Module 클래스 ( app.module.ts )

imports에 UsersModule 추가

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';
import { UsersModule } from './v1/users/user.module';

@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 ],
    }),
    UsersModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

실행