错误
RepositoryNotFoundError:找不到“UserQueryRepository”的存储库。看起来这个实体没有在当前的“默认”连接中注册?
版本
- @nestjs/typeorm - 7.1.5
- @nestjs/common - 7.6.15
- @nestjs/核心 - 7.6.15
- 节点 - 12.21.0
- typeorm - 0.2.34
问题描述
我有 2 个项目:common & microservice-1
通用包有 QueryService 和 QueryRepository 并且 microservice-1 应该从这些文件扩展。
所以在微服务 1 中,我有从 QueryService 扩展的 UserQueryService 和从 QueryRepository 扩展的 UserQueryRepository。
查询.repository.ts
import { FindManyOptions, Repository } from 'typeorm';
export class QueryRepository<Entity> extends Repository<Entity> {
findAll(options?: FindManyOptions<Entity>): Promise<Entity[]> {
return this.find(options);
}
}
查询.service.ts
import { FindManyOptions } from 'typeorm';
import { QueryRepository } from '../repository';
export class QueryService<Entity> {
constructor(protected readonly repository: QueryRepository<Entity>) {}
findById(id: string): Promise<Entity> {
return this.repository.findOne(id);
}
findAll(options?: FindManyOptions<Entity>): Promise<Entity[]> {
return this.repository.findAll(options);
}
}
user.query.repository.ts
import { QueryRepository } from '@project/common';
import { EntityRepository, Repository } from 'typeorm';
import { UserEntity } from '../entity';
@EntityRepository(UserEntity)
export class UserQueryRepository
extends QueryRepository<UserEntity> { // -> throws error
// extends Repository<UserEntity> { // -> works without extending from common
}
user.query.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { QueryService } from '@project/common';
import { UserEntity } from '../entity';
import { UserQueryRepository } from '../repository';
@Injectable()
export class UserQueryService extends QueryService<UserEntity> {
constructor(
@InjectRepository(UserQueryRepository)
repository: UserQueryRepository,
) {
super(repository);
}
getAllUsers(): Promise<UserEntity[]> {
return this.findAll();
}
}
用户模块.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from '../controller';
import { UserQueryRepository } from '../repository';
import { UserQueryService } from '../service';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'pass',
database: 'dbname',
autoLoadEntities: true,
synchronize: true,
}),
TypeOrmModule.forFeature([UserQueryRepository]),
],
controllers: [UserController],
providers: [UserQueryService],
})
export class UserModule {}