react-magnetic-di
Version:
Context driven dependency injection
41 lines (40 loc) • 2.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.injectable = injectable;
var _constants = require("./constants");
var _utils = require("./utils");
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function injectable(from, implementation) {
var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
displayName = _ref.displayName,
target = _ref.target,
_ref$track = _ref.track,
track = _ref$track === void 0 ? true : _ref$track,
_ref$global = _ref.global,
global = _ref$global === void 0 ? false : _ref$global;
var impl = implementation;
if (typeof impl === 'function') {
impl.displayName = displayName || (0, _utils.getDisplayName)(impl) || (0, _utils.getDisplayName)(from, 'di');
} else if (_typeof(impl) !== 'object') {
impl = _defineProperty({}, Symbol.toPrimitive, function () {
return implementation;
});
}
if (_constants.diRegistry.has(impl) && _constants.diRegistry.get(impl).from !== from) {
(0, _utils.warnOnce)("You are trying to use replacement \"".concat(displayName || impl.displayName, "\" on multiple injectables. ") + "That will override only the last dependency, as each replacement is uniquely linked.");
}
_constants.diRegistry.set(impl, {
value: implementation,
from: from,
targets: target && new WeakSet(Array.isArray(target) ? target : [target]),
track: track,
global: global,
cause: track ? new Error('Injectable created but not used. If this is on purpose, add "{track: false}"') : null
});
return impl;
}