mmlpx
Version:
mobx model layer paradigm
91 lines (81 loc) • 3.42 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
var _tslib = require('tslib');
var tslib_1 = _interopRequireWildcard(_tslib);
var _lruCache = require('lru-cache');
var _lruCache2 = _interopRequireDefault(_lruCache);
var _hydrate = require('./hydrate');
var _hydrate2 = _interopRequireDefault(_hydrate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var Injector = /** @class */function () {
function Injector(container) {
this.container = container || new _lruCache2.default();
}
Injector.newInstance = function (container) {
return new Injector(container);
};
Injector.prototype._getContainer = function () {
return this.container;
};
Injector.prototype.get = function (InjectedClass, options) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var scope = options.scope,
name = options.name;
var container = this.container;
var instance;
switch (scope) {
case "singleton" /* Singleton */:
if (name) {
instance = container.get(name);
if (!instance) {
instance = new (InjectedClass.bind.apply(InjectedClass, [void 0].concat(args)))();
// only singleton injection will be stored
container.set(name, instance);
} else {
var hydration = _hydrate2.default.apply(void 0, [instance, InjectedClass].concat(args));
// when the stored instance is deserialized object(from snapshot), we need to restore the hydration instance
if (instance !== hydration) {
instance = hydration;
container.set(name, hydration);
}
}
break;
}
throw new SyntaxError('A singleton injection must have a name!');
case "prototype" /* Prototype */:
instance = new (InjectedClass.bind.apply(InjectedClass, [void 0].concat(args)))();
break;
default:
throw new SyntaxError('You must set injected class as a mmlpx recognized model!');
}
return instance;
};
Injector.prototype.dump = function () {
return this.container.dump().reduce(function (acc, entry) {
var _a;
return tslib_1.__assign({}, acc, (_a = {}, _a[entry.k] = entry.v, _a));
}, {});
};
Injector.prototype.load = function (snapshot) {
var cacheArray = Object.keys(snapshot).map(function (k) {
return {
k: k,
v: snapshot[k],
e: 0
};
});
this.container.load(cacheArray);
};
return Injector;
}(); /**
* Created by Kuitos
* @homepage https://github.com/kuitos/
* @since 2017/12/25
*/
exports.default = Injector;
;