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