03) 개인프로젝트) DB를 사용 테스트 작성

Leo·2021년 2월 11일
1

Project-01

목록 보기
3/12
post-thumbnail

엔티티를 생성하여 값 얻기

먼저 User 모듈을 생성합니다.
Nest에서는 nest cli를 이용하여 명령어로 생성할 수 있습니다.
cli 명령어는 터미널에 nest를 치면 확인이 가능합니다.

$ nest g mo Users

명령어가 성공적으로 수행이 되면 app.module.ts의 import 부분에
UsersModule이 추가되어 있습니다.

user.entity.ts 파일을 만들어 줍니다.

/src/users/user.entity.ts

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

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column({ default: true })
  isActive: boolean;
}

UsersService와 usersController를 만들어줍니다.

$ nest g s Users
$ nest g co Users

Users.module.ts를 다음과 같이 해주면됩니다.

/src/users/Users.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';

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

forFeature()메서드를 사용하여 현재 범위에 등록된 저장소를 정의합니다.

실행하여 DB를 확인해보면 Entity Class의 이름의 Table이 만들어졌으며 해당 Table 안에는 작성한 항목 그대로 Column이 만들어져 있습니다.

Table : user
Column : id, firstName, lastName, isActive

이렇게 DB Table이 자동으로 만들어져 있습니다.
각각의 Column의 설정은 해당 Entity의 Decorator을 이용하여 설정해 줄 수 있습니다.

작성한 Entity의 테스트를 위한 작성

Entity를 이용하여 Table과 Column을 구성하였습니다.
이젠 해당 Table의 값을 불러오는 것을 할 수 있습니다.

Service를 이용하여 DB의 데이터를 가져오도록합니다.
Nest CLI를 이용하여 service를 만들어 줍니다.

$ nest g s Users

/src/users/Users.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: string): Promise<User> {
    return this.usersRepository.findOne(id);
  }

  async remove(id: string): Promise<void> {
    await this.usersRepository.delete(id);
  }
}

Service를 통해 DB에 접속하여 처리를 하게 됩니다.
findAll은 해당 테이블의 모든 행을 가져옵니다.
findOne은 id에 해당되는 행을 가져옵니다.
remove는 id에 해당되는 행을 지웁니다.

이제 Service 사용하며 URI를 통해 접근이 가능하도록
Controller를 만들어 주겠습니다.

$ nest g co Users

/src/users/users.controller.ts

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

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  findAll(): Promise<User[]> {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param() id: string): Promise<User> {
    return this.usersService.findOne(id);
  }

  @Delete(':id')
  async remove(@Param() id: string): Promise<void> {
    await this.usersService.remove(id);
  }
}

3개의 요청을 처리할 수 있게 되었습니다.
테스트 요청을 보내기 위하여 DB에 데이터를 입력해 주겠습니다.

insert into user values(1,'jong1', 'lee', true);
insert into user values(2,'jong2', 'leo', true);
insert into user values(3,'jong3', 'ki', false);

데이터가 정상적으로 들어갔다면 요청을 통해 정상적으로 작동하는지 보도록하겠습니다.

GET localhost:3000/users/
findAll이 사용됩니다.

[
    {
        "id": 1,
        "firstName": "jong1",
        "lastName": "lee",
        "isActive": true
    },
    {
        "id": 2,
        "firstName": "jong2",
        "lastName": "leo",
        "isActive": true
    },
    {
        "id": 3,
        "firstName": "jong3",
        "lastName": "ki",
        "isActive": false
    }
]

json형식의 데이터로 정상적으로 요청에 대한 응답이 왔습니다.
해당 응답을 통해 형식을 알 수 있습니다.
조회된 행은 JSON Object에 담기며 여러개의 행이 조회가 되면
JSON Array에 담기게 됩니다. 그리고 행은 컬럼이 Key 값이 Value 형식으로 응답이 옵니다.

GET localhost:3000/users/2
findOne이 사용됩니다.

{
    "id": 2,
    "firstName": "jong2",
    "lastName": "leo",
    "isActive": true
}

URI에 2를 넣어줬기 때문에 id가 2에 해당하는 행을 가져옵니다.

DELETE localhost:3000/users/2
remove가 사용됩니다. 확인을 위해 findAll을 해줍니다.
GET localhost:3000/users/

[
    {
        "id": 1,
        "firstName": "jong1",
        "lastName": "lee",
        "isActive": true
    },
    {
        "id": 3,
        "firstName": "jong3",
        "lastName": "ki",
        "isActive": false
    }
]

정상적으로 삭제가 되었습니다.

profile
개발자

0개의 댓글