我正在尝试通过实现一个干净的架构结构来测试Nestjs,并且想验证我的解决方案,因为我不确定我是否知道执行此操作的最佳方法。请注意,该示例几乎是伪代码,并且缺少许多类型或泛型,因为它们不是讨论的重点。
从我的域逻辑开始,我可能想在类似于以下类的类中实现它:
@Injectable()
export class ProfileDomainEntity {
async addAge(profileId: string, age: number): Promise<void> {
const profile = await this.profilesRepository.getOne(profileId)
profile.age = age
await this.profilesRepository.updateOne(profileId, profile)
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我需要访问profileRepository,但是按照干净架构的原理,我现在不想为实现而烦恼,所以我为此写了一个接口:
interface IProfilesRepository {
getOne (profileId: string): object
updateOne (profileId: string, profile: object): bool
}
Run Code Online (Sandbox Code Playgroud)
然后,将依赖项注入到ProfileDomainEntity构造函数中,并确保它遵循预期的接口:
export class ProfileDomainEntity {
constructor(
private readonly profilesRepository: IProfilesRepository
){}
async addAge(profileId: string, age: number): Promise<void> {
const profile = await this.profilesRepository.getOne(profileId)
profile.age = age
await this.profilesRepository.updateOne(profileId, profile)
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个简单的内存实现,让我运行代码:
class ProfilesRepository …Run Code Online (Sandbox Code Playgroud) domain-driven-design dependency-injection typescript clean-architecture nestjs