NodeJS: как реализовать шаблон хранилища - PullRequest
0 голосов
/ 29 мая 2018

Я хотел бы реализовать шаблон 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" вместо набора лиц) - Другие идеи?

Спасибо за помощь!Я пытаюсь решить эту проблему часами ...

1 Ответ

0 голосов
/ 31 мая 2018

Решил сам.Проблема заключалась в круговой зависимости между двумя модулями.Проблема устранена путем перемещения require с после module.exports.

Ссылка: http://blog.cloudmineinc.com/managing-cyclic-dependencies-in-node.js?hsFormKey=ae1b2c3916d0a2be7aafb5d841ce24c0

...