How to implement TypeORM 0.3.x custom repository in NestJS?

212 views Asked by At

I'm trying to make a custom repository in TypeORM (^0.3.0) and use it in NestJS, but the old way (using @EntityRepository) has been deprecated and I've tried the answer from this post and this one, but I get an error.

The code:

@Injectable()
export class TaskRepository<Task> extends Repository<Task> {
  constructor(private dataSource: DataSource) {
    super(Task, dataSource.createEntityManager());
  }

  async findByName(name: string): Promise<Task> {
    try {
      return await this.findOneBy({ name });
      // these don't work either, same error
      // return await this.findOneBy({ name: name });
      // return await this.findOneBy({where: { name: name }});
      // return await this.findOne({ name });
      // return await this.findOne({where: { name: name }});

The error I get when I hover over name property I want to search for:

Argument of type '{ name: string; }' is not assignable to parameter of type 'FindOneOptions<Task>'.  
Object literal may only specify known properties, and 'name' does not exist in type 'FindOneOptions<Task>'.

Task entity:

@Entity()
@Unique(['name'])
export class Task {
  @PrimaryGeneratedColumn('uuid')
  @IsOptional()
  task_id: string;

  @Column({ length: 50 })
  @IsString()
  @IsNotEmpty()
  name: string;
  //...

When I create the repository directly inside my service, I can use the findOneBy with no issue at all:

@Injectable()
export class TasksService {
  constructor(
    @InjectRepository(Task) private taskRepository: Repository<Task>,
  ) {}

  async findOne(id: string) {
    try {
      // works fine
      return await this.taskRepository.findOneBy({ task_id: id });
    } catch (error) {
      console.log(error);
    }
  }

I've tried answers from other posts as well, but all of them lead me to this same problem, which makes me think I'm doing something wrong.

I hope someone can help me with this :)

0

There are 0 answers