bit*_*its 5 repository-pattern node.js
我想在我的 NodeJS 应用程序中实现存储库模式,但我遇到了循环需求的麻烦(我猜......)。
我如何尝试实现它:
首先:我的存储库模式设计正确吗?
我的课程:
personRepository.js
const PersonModel = require('./model');
const Person = require('./person');
class PersonRepository {
constructor() {
this._persons = new Set();
}
getAll( cb ) { // To Do: convert to promise
let results = new Set();
PersonModel.find({}, 'firstName lastName', (err, people) => {
if (err) {
console.error(err);
}
people.forEach((person, index) => {
let foundPerson = new Person(person._id.toString(), person.firstName, person.lastName, person.email, person.birthday);
results.add(foundPerson);
});
this._persons = results;
if (cb) cb(this._persons);
});
}
getById(id) {
return PersonModel.findOne({ _id: id });
}
getByEmail(email) {
throw new Error("Method not implemented");
}
create( person ) {
throw new Error("Method not implemented");
}
update ( person ) {
throw new Error("Method not implemented");
}
delete ( person ) {
throw new Error("Method not implemented");
}
}
module.exports = new PersonRepository();
Run Code Online (Sandbox Code Playgroud)
person.js
const PersonModel = require('./model');
const personRepository = require('./personRepository');
class Person {
constructor(personId, first, last, email, birthday) {
this._id = personId ? personId : undefined;
this._firstName = first ? first : undefined;
this._lastName = last ? last : undefined;
this._email = email ? email : undefined;
this._birthday = birthday ? new Date(birthday) : undefined;
this._relations = new Map();
}
init() { // Get all data from database
personRepository.getById(this._id)
.then(console.log)
.catch(console.error);
}
}
module.exports = Person;
Run Code Online (Sandbox Code Playgroud)
测试.js
console.log("--- GET ALL : results--- ");
personRepository.getAll( (persons) => {
for (let person of persons) {
person.loadAllData()
.then(() => {
console.log(person);
})
.catch((e) => {
console.log(e);
});
}
});
console.log("--- INIT : results--- ");
var personInit = new Person("59c18a9029ef510012312995");
console.log("before init");
console.log(personInit);
personInit.init();
console.log("after init");
console.log(personInit);
Run Code Online (Sandbox Code Playgroud)
问题: 当运行“获取全部”测试(没有 INIT 测试)时,它可以工作。当我添加 INIT 测试时,出现错误:
personRepository.getById(this._id)
^
TypeError: personRepository.getById is not a function
at Person.init
Run Code Online (Sandbox Code Playgroud)
我怎样才能防止这种情况发生?- 改变我需要模块的方式?- 改变我的设计?(例如,不需要 personRepository 中的 Person 类,只需在“getAll”中创建一组 id,而不是一组人员) - 其他想法?
谢谢你帮助我!我现在正在尝试解决这个问题几个小时......
我自己解决了。问题是两个模块之间的循环依赖。require通过将s 移到 后面即可解决问题module.exports。
参考:https://coderwall.com/p/myzvmg/circular-dependency-in-node-js
| 归档时间: |
|
| 查看次数: |
17887 次 |
| 最近记录: |