UNPKG

mmlpx

Version:

mobx model layer paradigm

73 lines 2.77 kB
/** * Created by Kuitos * @homepage https://github.com/kuitos/ * @since 2017/12/25 */ import * as tslib_1 from "tslib"; import LRUCache from 'lru-cache'; import hydrate from './hydrate'; var Injector = /** @class */function () { function Injector(container) { this.container = container || new LRUCache(); } 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 = hydrate.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; }(); export default Injector;