【发布时间】:2018-05-29 19:57:45
【问题描述】:
我想在我的 NodeJS 应用程序中实现存储库模式,但我遇到了循环需求的麻烦(我猜是...)。
我是如何尝试实现它的:
- PersonRepository 类的方法:getAll、getById、create、update、delete
- 具有以下方法的 Person 类:init、createAccount、showRelations、addRelation,
首先:我的存储库模式设计是否正确?
我的课:
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 而不是一组人员) - 其他想法?
感谢您帮助我!我正在尝试解决这个问题好几个小时......
【问题讨论】:
标签: node.js repository-pattern