Search code examples
typescripttypeorm

TypeORM: Create BaseRepository class


How to create baseRepository class that extends TypeORM's Repository

    import { Repository } from 'typeorm';

    export abstract class BaseRepo extends Repository<T> {

        public getAll () { ... }

        public getOneById (id: number) { ... }

        public deleteById (id: number) { ... }

    }

and then inherit those methods like

    @EntityRepository(User)
    export class UserRepo extends BaseRepo<User> {

        constructor (baseRepo: BaseRepo) {
            super();
            this.__baseRepo = baseRepo;
        }

        public getOne (id: number) {
            return __baseRepo.getOneById(id);
        }
    }

Solution

  • This solution works without constructor

    import { Repository } from "typeorm";
    
    export class BaseRepo<T> extends Repository<T> {
    
       getOneById(id: string) { ... }
    
    }
    

    and use it like

    import { EntityRepository } from "typeorm";
    import { BaseRepo } from "../shared/BaseRepo";
    import { User } from "../entities/User";
    
    @EntityRepository(User)
    export class MyEntityRepository extends BaseRepo<User> { }