我想在我的NodeJS应用中实现Repository模式,但是我遇到了循环需求的麻烦(我想...)。
我如何实现它:
首先:我的存储库模式设计正确吗?
我的班级:
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();
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;
tests.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);
问题:运行“全部获取”测试(不使用INIT测试)时,它可以工作。当我添加INIT测试时,出现错误:
personRepository.getById(this._id)
^
TypeError: personRepository.getById is not a function
at Person.init
如何防止这种情况发生?-更改我需要模块的方式?-更改我的设计? (例如,不需要在personRepository中使用Person类,而只需在“ getAll”中创建一组ID而不是一组Person)-其他想法?
感谢您的帮助!我正在尝试解决这个问题几个小时...
我自己解决了。问题是两个模块之间存在循环依赖关系。通过将require
移到module.exports
之后解决了问题。
参考:https://coderwall.com/p/myzvmg/circular-dependencies-in-node-js