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.
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.
Hope helpful for you:
import { DataSource, Repository } from 'typeorm';
import { EntityTarget } from 'typeorm/common/EntityTarget';
export class GenericRepository<T> extends Repository<T> {
constructor(target: EntityTarget<T>, dataSource: DataSource) {
super(target, dataSource.createEntityManager());
}
async someCommonMethod() {
return {};
}
}
import { DataSource } from 'typeorm';
import { User } from '../../entities/User';
import { Injectable } from '@nestjs/common';
import { GenericRepository } from '../common/generic.repository';
@Injectable()
export class UserRepository extends GenericRepository<User> {
constructor(private dataSource: DataSource) {
super(User, dataSource.createEntityManager());
}
}
import { Injectable } from '@nestjs/common';
import { User } from '../../entities/User';
import { InjectRepository } from '@nestjs/typeorm';
import { UsersRepository } from './users.repository';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private readonly usersRepository: UsersRepository,
) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With