Search code examples
javascriptnode.jsnestjsrepositorytypeorm

TypeORM generic findByOne, FindOptionsWhere error


I have a Nestjs project using TypeORM. I create BaseRepositoryInterface and BasRepository abstract class. Here is the BaseRepositoryInterface:

import { DeepPartial, FindManyOptions } from "typeorm";

export interface BaseRepositoryInterface<T> {
    create(data: DeepPartial<T>): T
    findOneById(id: number): Promise<T>
    findAll(options?: FindManyOptions<T>): Promise<T[]>
}

and the BaseRepository class:

import { DeepPartial, FindManyOptions, FindOptionsWhere, Repository } from "typeorm";
import { BaseRepositoryInterface } from "./base.interface.repository";

export abstract class BaseRepository<T> implements BaseRepositoryInterface<T> {
    private entity: Repository<T>;

    protected constructor(entity: Repository<T>) {
        this.entity = entity;
    }

    public create(data: DeepPartial<T>): T {
        return this.entity.create(data)
    }

    public async findOneById(id: number): Promise<T> {
        const options: FindOptionsWhere<T> = { id: id } // here is the error
        return await this.entity.findOneBy(options)
    }

    public async findAll(options?: FindManyOptions<T>): Promise<T[]> {
        return await this.entity.find(options)
    }
}

But I got the error in findOneBy method. The error is:

enter image description here

How can I fix this error? I found the issue in typeorm github page, but the problem didn't solve yet.


Solution

  • firstly you need to define id as number by using IEntity interface then T extends IEntity

    import { DeepPartial, FindManyOptions , FindOneOptions } from "typeorm";
    
    export interface IEntity {
      id: number;
    }
    
    export interface BaseRepositoryInterface<T> {
        create(data: DeepPartial<T>): T
        findOneById(id: number): Promise<T | null>
        findAll(options?: FindManyOptions<T>): Promise<T[]>
    }
    
    import { FindOptionsWhere, Repository } from "typeorm";
    
    export abstract class BaseRepository<T extends Record<string, any> & IEntity> implements BaseRepositoryInterface<T> {
        private entity: Repository<T>;
    
        protected constructor(entity: Repository<T>) {
            this.entity = entity;
        }
    
        public create(data: DeepPartial<T>): T {
            return this.entity.create(data)
        }
    
        public async findOneById(id: number): Promise<T | null> {
           const options: FindOneOptions<T> = {
          where: {
            id: id,
          } as FindOptionsWhere<T>,
        };
        return await this.entity.findOne(options);
        }
    
        public async findAll(options?: FindManyOptions<T>): Promise<T[]> {
            return await this.entity.find(options)
        }
    }