【发布时间】:2020-05-06 18:22:03
【问题描述】:
我正在使用 Nest.js + TypeORM,但在尝试向服务类添加继承时遇到了问题。
我想要一个从 Base 服务类扩展而来的用户服务类,继承它拥有的所有方法。
这就是我所做的:
export class BaseService<T> {
private repo;
constructor(repo: Repository<T>){
this.repo = repo;
}
async findAll(opts?): Promise<T[]> {
return this.repo.find(opts);
}
......
}
然后在我的用户服务上:
export class UserService extends BaseService<User> {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
private readonly mailerService: MailerService,
) {
super(userRepository);
}
}
这很好用,我只需要 Service 类中的单个存储库,但一旦我需要更多,例如 productRepository,正如您所见,由于构造函数被硬编码以接受单个存储库,它会失败。
我似乎无法弄清楚实现此类目标的最优雅方式是什么。
有人知道吗?
【问题讨论】:
-
您的意思是在您的
BaseService类中再使用一个存储库吗? -
@kkkkkkkk 不,它可以是任意数量的存储库。在某些服务中,它可能需要 3 个 repos,而在其他服务中可能只需要 1 个。
-
是的,但那些是你的子类,不是你的
BaseService对吗?你的BaseService只能实现你所有子类之间的通用逻辑。对于特定于某些子类的东西,您应该将它们保留在这些子类中。