Node.js - определение свойства дочернего класса в конструкторе родителя - PullRequest
0 голосов
/ 09 января 2019

Я использую суперфункцию ООП - наследование. Итак, у меня есть стек дочерних классов, которые имеют то же свойство, но значение этого свойства зависит от класса. Я хочу поместить определение этого свойства в конструктор родителя, но я не знаю, как передать ему значение.

Сейчас я использую npm-пакет config, но чем больше у меня дочерних классов, тем больше становится config-file. Итак, я хотел бы иметь файлы типа child_*.yaml с конфигурацией для каждого дочернего элемента, но я не могу понять , как я могу импортировать необходимый файл конфигурации для правильного определения свойства дочернего элемента .

app.js (точка входа):

const util = require('util');
const Factory = require('./src/factory');

console.log('\nInput child name (ex. \'child_one\') and press \'Enter\':\n');
process.stdin.on('data', function (data) {
  const input = data.toString().split('\n')[0];

  const child = Factory.createChild({child_name: input});
  console.log(`configuration: \n\t${util.inspect(child.configuration, null, 10)}`);
});

ЦСИ / factory.js

const ChildOne = require('./children').child_one;
const ChildTwo = require('./children').child_two;
const ChildThree = require('./children').child_three;;

class Factory {
  static _supported_children (child_name) {
    switch (child_name) {
      case 'child_one':
        return ChildOne;
      case 'child_two':
        return ChildTwo;
      case 'child_three':
        return ChildThree;
      default:
        return ChildOne;
    }
  }

  static getConstructor (child_name = 'child_one') {
    return Factory._supported_children(child_name);
  }

  static createChild(data, ...args) {
    return new (Factory.getConstructor(data.child_name))(data, ...args);
  }
}

module.exports = Factory;

ЦСИ / children.js

const Parent = require('./parent');

class ChildOne extends Parent {}
class ChildTwo extends Parent {}
class ChildThree extends Parent {}

module.exports = {
  child_one: ChildOne,
  child_two: ChildTwo,
  child_three: ChildThree,
};

ЦСИ / parent.js

const settings = require('config');

const VALUES = settings.get('prop_s');

class Parent {
  constructor(data) {

    this.configuration = Object.assign({}, { prop: VALUES[data.child_name] });
  }
}
module.exports = Parent;

конфиг / default.yaml

some_other_properties:
  property: '123'

prop_s:
  child_one:
    a: 1
    b: '2'
    c: 3
  child_two:
    d: 4
    e: 5
  child_three:
    f: '6'
    g: '7'
    h: '8'
    i: '9'
...