TIL. 22 NestJS Query

박경철·2023년 5월 22일

TypeORM에서 제공해주는 함수가 아닌 Query를 사용하여 CRUD를 구현

1. NestJS DB Setting

  • 이전 TypeORM 작업 시 동일하게 설정

2. Entity

  • synchronize 속성 값을 True로 사용하여 정의된 Entity의 Table을 자동 생성하여 사용.(미리 DB에 Table을 생성하여도 됨.)
  • 정의된 Entity를 Module에 Import

3. Service

import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { CreateBoardDto } from './dto/create-board.dto';
import { UpdateBoardDto } from './dto/update-board.dto';
import { Board } from './entities/board.entity';

@Injectable()
export class BoardsService {
  constructor(@InjectEntityManager() private entityManager: EntityManager){}

  async create(createBoardDto: CreateBoardDto) {
    return await this.entityManager.transaction(async() => {
      await this.entityManager.query(`INSERT INTO boards(title, contents) 
      values('${createBoardDto.title}','${createBoardDto.contents}');`);
    })
  }

  async findAll(): Promise<Board> {
    return await this.entityManager.transaction(async() => {
      return await this.entityManager.query(`SELECT * FROM boards;`);
    })
  }

  async findOne(id: number) {
    return await this.entityManager.transaction(async() => {
      return await this.entityManager.query(`SELECT * FROM boards WHERE id=${id};`);
    })
  }

  async update(id: number, updateBoardDto: UpdateBoardDto) {
    return await this.entityManager.transaction(async() => {
      await this.entityManager.query(`UPDATE boards SET title='${updateBoardDto.title}',
       contents='${updateBoardDto.contents}' WHERE id=${id}`);
    })
  }

  async remove(id: number) {
    return await this.entityManager.transaction(async() => {
      await this.entityManager.query(`DELETE FROM boards WHERE id=${id}`);
    })
  }
}

4. Test

  • synchronize 속성 값을 True로 설정하여 자동으로 Table이 생성됨.
profile
안녕하세요!

0개의 댓글