Я хотел бы реализовать шаблон Repository в моем приложении 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
Как я могу предотвратить это?- Изменить способ, которым мне нужны мои модули?- Изменить мой дизайн?(например, не требуйте класса Person в personRepository и просто создайте набор идентификаторов в "getAll" вместо набора лиц) - Другие идеи?
Спасибо за помощь!Я пытаюсь решить эту проблему часами ...