[NestJS] EntityRepository is deprecated 해결

soyeon·2023년 4월 7일

Nest

목록 보기
4/10
post-thumbnail

@EntityRepository is deprecated 라는 문제를 대면했다.
지금부터 CustomRepository를 기존 typeorm 에서 제공하는 Repositot<entity>를 사용하면서 CustomRepository를 작성하는 방법을 여러가지 참고하여 해당 문제를 해결한 결과를 작성해두었다.

typeORM_공식문서 를 기반으로 작성했다.

1. TypeOrm 엔터티 생성

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

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

  @Column()
  title: string;

  @Column()
  description: string;

  @Column({ default: false })
  completed: boolean;
}

2. Repository 클래스 생성

import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { Todo } from './todo.entity';

@Injectable()
export class TodoRepository extends Repository<Todo> {
  constructor(private dataSource: DataSource) {
    super(Todo, dataSource.createEntityManager());
  }
  async getById(id: number): Promise<Todo> {
    return await this.findOneBy({ id });
  }
}

3. TodosService 클래스 작성

import { Injectable, NotFoundException } from '@nestjs/common';
import { TodoRepository } from './todo.repository';
import { Todo } from './todo.entity';

@Injectable()
export class TodoService {
  constructor(private readonly todoRepository: TodoRepository) {}

  async getTodoById(id: number): Promise<Todo> {
    const found = await this.todoRepository.getById(id);

    if (!found) {
      throw new NotFoundException(`Can't find Todo with id ${id}`);
    }
    return found;
  }
}

4. TodosModule에서 필요한 정보 업데이트

TodoModule에서 알 수 있도록 providers에 추가하기

import { Module } from '@nestjs/common';
import { TodoController } from './todo.controller';
import { TodoService } from './todo.service';
import { TodoRepository } from './todo.repository';

@Module({
  controllers: [TodoController],
  providers: [TodoService, TodoRepository],
})
export class TodoModule {}
profile
사부작 사부작

0개의 댓글