TypeORM 패키지 설치

$ npm install --save @nestjs/typeorm typeorm mysql2

 

MySQL 설치

 

[MacOS] MySQL 설치

brew 설치 $ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" Homebrew Site MySQL 설치, 설정 # Installation $ brew install mysql # version $ mysql -V # server start $ mysql.server start # server stop $ my

clichy12.tistory.com

 

User 테이블 생성

CREATE TABLE `User` (
  `idx` bigint unsigned NOT NULL AUTO_INCREMENT,
  `id` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `createDt` timestamp NULL DEFAULT NULL,
  `updateDt` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`idx`)
)

 


 

# res: resource
$ nest g res user

spec.ts 파일은 삭제


src/config/typeorm.config.service.ts

더보기
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from "@nestjs/typeorm";
import { ConfigService } from "@nestjs/config";
import { Injectable } from "@nestjs/common";

@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {

    constructor(private readonly configService: ConfigService) { }

    createTypeOrmOptions(connectionName?: string): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {

        return {
            type: 'mysql',
            host: this.configService.get('DB.MYSQL.HOST'),
            port: this.configService.get('DB.MYSQL.PORT'),
            username: this.configService.get('DB.MYSQL.USER'),
            password: String(this.configService.get('DB.MYSQL.PASSWORD')),
            database: this.configService.get('DB.MYSQL.DATABASE'),
            entities: [],
            synchronize: false,
            autoLoadEntities: true
        }
    }

}

 

entities : TypeORM에 Entity를 명시적으로 알린다, autoLoadEntities: true 를 사용하기 때문에 빈 배열을 넣었다

synchronize : 운영 환경에서 true 값을 사용하게 되면, 데이터가 손상될 수 있다

autoLoadEntities : true 일 경우, Entity가 자동으로 로드된다. forFeature() 선언을 통해 자동으로 추가될 예정

  • user.module.ts에서 TypeOrmModule.forFeature를 통해 선언 할 예정

src/app.module.ts

더보기
...
import { TypeOrmModule } from '@nestjs/typeorm';
import { TypeOrmConfigService } from './config/typeorm.config.service';

@Module({
  imports: [
  		...
  	, TypeOrmModule.forRootAsync({
      useClass: TypeOrmConfigService
    })],
	...
})
export class AppModule implements NestModule {
	...
}

src/user/entities/user.entity.ts

더보기
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    idx: number;

    @Column()
    id: string;

    @Column()
    password: string;

    @Column()
    name: string;

    @Column()
    createDt: Date;

    @Column()
    updateDt: Date;
}

 

데이터베이스 User 테이블과 동일한 속성으로 선언


src/user/user.module.ts

더보기
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

$ npm i class-validator

 

데코레이터(@) 선언만으로  API 요청 시, 데이터 검증을 자동으로 해준다

@IsOptional()을 선언하지 않으면 해당 속성은 필수 속성이 된다

 


src/user/dto/create-user.dto.ts

더보기
import { IsDate, IsOptional, IsString, Length } from 'class-validator';

export class CreateUserDto {

    @Length(5, 50)
    @IsString()
    readonly id: string;

    @IsString()
    readonly password: string;

    @IsString()
    readonly name: string;

    @IsOptional()
    @IsDate()
    readonly createDt: Date = new Date();

    @IsOptional()
    @IsDate()
    readonly updateDt: Date = new Date();

}

src/user/dto/update-user.dto.ts

더보기
import { IsDate, IsOptional, IsString } from 'class-validator';

export class UpdateUserDto {

    @IsOptional()
    @IsString()
    readonly password: string;

    @IsString()
    readonly name: string;

    @IsOptional()
    @IsDate()
    readonly updateDt: Date = new Date();

}

src/user/user.service.ts

더보기
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {

  constructor(@InjectRepository(User) private userRepository: Repository<User>) { }

  async create(createUserDto: CreateUserDto) {
    const user = await this.findOne(createUserDto.id);

    if (user.length > 0) {
      return [];
    }

    return await this.userRepository.save(createUserDto);
  }

  async findAll() {
    return await this.userRepository.find();
  }

  async findOne(id: string) {
    return await this.userRepository.find({ select: ['idx', 'id', 'name', 'createDt', 'updateDt'], where: { id } })
  }

  update(id: string, updateUserDto: UpdateUserDto) {
    console.log(id, updateUserDto);

    return this.userRepository.update({ id }, updateUserDto);
  }

  remove(id: string) {
    return this.userRepository.delete({ id });
  }
}

src/user/user.controller.ts

더보기
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  @Get()
  findAll() {
    return this.userService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.userService.findOne(id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(id);
  }
}

$ npm i class-transformer

 

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

...
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true
    })
  )
...

ValidationPipe 선언만으로 검증을 해줄 수 있다

 

 


참고 링크

https://docs.nestjs.com/techniques/validation

https://velog.io/@artlogy/08.-Validate

https://docs.nestjs.com/techniques/database

https://codegear.tistory.com/116

'JavaScript > NestJS' 카테고리의 다른 글

[NestJS] Exception filters  (0) 2023.08.21
[NestJS] Swagger 적용하기  (0) 2023.08.21
[NestJS] 환경 변수 (config) 사용하기  (0) 2023.08.20
[NestJS] Logging 하기  (0) 2023.08.19
[NestJS] Jest 테스트하기  (0) 2023.08.17

+ Recent posts