我想在我的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) - 其他想法?
谢谢你的帮助!我现在试图解决这个问题几个小时......
答案 0 :(得分:1)
自己解决了。问题是两个模块之间存在循环依赖关系。通过在require
之后移动module.exports
来解决问题。