brusc
Version:
IOC Container for Effective JS development
88 lines (67 loc) • 2.97 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Container = void 0;
var _utils = require("../common/utils");
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var Container = /*#__PURE__*/function () {
function Container(_ref) {
var instanceProviders = _ref.instanceProviders,
adapters = _ref.adapters;
_classCallCheck(this, Container);
this._instanceProviders = instanceProviders;
this._adapters = adapters;
this._keptInstances = new Map();
this._circularDependencyControl = new Set();
}
_createClass(Container, [{
key: "provide",
value: function provide(key) {
if (this._keptInstances.has(key)) {
return this._keptInstances.get(key);
}
this._guardNotInCircularDependency(key);
this._guardHasInstanceProvider(key);
this._circularDependencyControl.add(key);
var instanceProvider = this._instanceProviders.get(key);
var instance = instanceProvider.provide(key);
this._circularDependencyControl.delete(key);
this._adapters.forEach(function (adapter) {
instance = adapter.process(key, instance);
});
if (instanceProvider.isSingleton) {
this._keptInstances.set(key, instance);
}
return instance;
}
}, {
key: "loadEagerInstances",
value: function loadEagerInstances() {
var _this = this;
Array.from(this._instanceProviders.values()).forEach(function (instanceProvider) {
return instanceProvider.isEager && _this.provide(instanceProvider.key);
});
}
}, {
key: "_guardNotInCircularDependency",
value: function _guardNotInCircularDependency(key) {
if (this._circularDependencyControl.has(key)) {
throw new Error("Circular dependency [".concat(Array.from(this._circularDependencyControl.values()).map(function (k) {
return (0, _utils.stringKey)(k);
}).join('->'), "->").concat((0, _utils.stringKey)(key), "]"));
}
}
}, {
key: "_guardHasInstanceProvider",
value: function _guardHasInstanceProvider(key) {
if (!this._instanceProviders.has(key)) {
throw new Error("No instance provider defined for [".concat((0, _utils.stringKey)(key), "]"));
}
}
}]);
return Container;
}();
exports.Container = Container;
;