Javascript port resolver (dependency injection)

Date: 2018-07-31
const getInstance = (fn) => {
    let _instance = null;
    return () => {
        if (!_instance) {
            _instance = fn();
        }
        return _instance;
    };
};

class PortResolver {
    constructor() {
        this._container = {};
    }
    register(name, fn) {
        if (typeof name !== 'string') {
            throw new Error('register expects a name string');
        }
        if (typeof fn !== 'function') {
            throw new Error('register expects a function');
        }
        this._container[name] = fn;
    }
    registerInstance(name, fn) {
        this.register(name, getInstance(fn));
    }
    resolve(name) {
        let fn = this._container[name];
        if (!fn) {
            throw new Error('PortResolver can not resolve ' + name);
        }
        return fn();
    }
}

module.exports = PortResolver;
const PortResolver = require('../adapters/PortResolver');
const currentPortResolver = require('../domain/currentPortResolver');

class Wiring {
    apply() {
        const portResolver = new PortResolver();
        portResolver.register('number', () => 8);

        currentPortResolver.setResolver(portResolver);
    }
}

module.exports = Wiring;
class CurrentPortResolver {
    constructor() {
        this.resolver = null;
    }
    resolve(name) {
        if (!this.resolver) {
          throw new Error('CurrentPortResolver not set');
        }
        return this.resolver.resolve(name);
    }
    setResolver(resolver) {
        this.resolver = resolver;
    }
}
module.exports = new CurrentPortResolver();

 

11900cookie-checkJavascript port resolver (dependency injection)