node.jsdependency-injectionormnestjstypeorm

How to extend TypeORM repository in NestJS 9 (TypeORM 3.+)


Previously, TypeORM repository could be extended and injected directly into services, e.g.:

import { User } from './entities/user.entity';
import { EntityRepository, Repository } from 'typeorm';

@EntityRepository(User)
export class UsersRepo extends Repository<User> {
  // my custom repo methods
}
import { Injectable } from '@nestjs/common'
import { UsersRepo } from './users.repo';

@Injectable()
export class UsersService {
  constructor(private readonly usersRepo: UsersRepo) {}
}

But since version 3.0.0 TypeORM does not support repository extending via inheritance.

How to achieve such behavior in NestJS 9 (which depends on TypeORM 3.+)? The only solution I came up with is to add custom methods to the service layer. But I would like to keep all ORM-related methods (query, aggregations, etc.) in the repository layer.


Solution

  • Let me tell you straight away: I have no idea whether this is a recommended solution, I don't know if the authors of TypeORM actually considered such approach at all. But what I just did a minute ago is this:

    @Injectable()
    export class UserRepository extends Repository<UserEntity> {
    
    
      constructor(
        @InjectRepository(UserEntity)
        repository: Repository<UserEntity>
      ) {
        super(repository.target, repository.manager, repository.queryRunner);
      }
    }
    

    And the best part: it worked :D

    I use: "@nestjs/typeorm": "^9.0.0" just so you know.

    I will keep checking if it doesn't break anything, but for now, seems like a good workaround.