【发布时间】:2019-05-15 13:21:46
【问题描述】:
我正在尝试根据我的ConfigService 中的值提供不同的服务。
我遇到的问题是,当执行findOne()(结果为null)或countDocuments()(结果为0)等查询方法时,注入的猫鼬模型不返回任何值。
我的服务类定义如下:
export class BaseService {
constructor(@InjectModel('Cat') public readonly catModel: Model<Cat>) {}
createService(option: string) {
if (option === 'OTHER') {
return new OtherService(this.catModel);
} else if (option === 'ANOTHER') {
return new AnotherService(this.catModel);
} else {
return new BaseService(this.catModel);
}
}
async findOne(id: string): Promise<Cat> {
return await this.catModel.findOne({_id: id});
}
async count(): Promise<number> {
return await this.catModel.countDocuments();
}
testClass() {
console.log('BASE SERVICE CLASS USED');
}
}
@Injectable()
export class OtherService extends BaseService {
constructor(@InjectModel('Cat') public readonly catModel: Model<Cat>) {
super(catModel);
}
testClass() {
console.log('OTHER SERVICE CLASS USED');
}
}
@Injectable()
export class AnotherService extends BaseService {
constructor(@InjectModel('Cat') public readonly catModel: Model<Cat>) {
super(catModel);
}
testClass() {
console.log('ANOTHER SERVICE CLASS USED');
}
}
这让我可以从我的提供商那里获得正确的服务(testClass() 打印出预期的字符串)。我的提供者如下所示:
export const catProviders = [
{
provide: 'CatModelToken',
useFactory: (connection: Connection) => connection.model('CAT', CatSchema),
inject: ['DbConnectionToken'],
},
{
provide: 'BaseService',
useFactory: (ConfigService: ConfigService, connection: Connection) => {
const options = ConfigService.get('SERVICE_TYPE');
let model = connection.model('CAT', CatSchema);
return new BaseService(model).createService(options);
},
inject: [ConfigService, 'CatModelToken', 'DbConnectionToken'],
}
];
所以我的问题分为两部分:
- 是否有更好的方法来处理正确类的创建和
避免必须为唯一创建一个
BaseService实例 打电话给createService()的目的是什么? - 将猫鼬模型注入新创建的服务的正确方法是什么?
我也不能使用文档中的 useClass 示例,因为我需要能够注入 ConfigService。
【问题讨论】:
标签: mongoose dependency-injection subclass extends nestjs