UNPKG

nucleux

Version:

Simple, atomic hub for all your React application's state management needs. No providers, no boilerplate, just state that works.

70 lines (69 loc) 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Container = void 0; const utils_1 = require("./utils"); class Container { static instance = new Container(); stores = new Map(); constructor() { if (Container.instance) { throw new Error('Error: Instantiation failed. Use Container.getInstance() instead.'); } Container.instance = this; } instantiate(storeDefinition) { if (this.stores.has(storeDefinition.storeId)) { console.warn(`Store record for ${storeDefinition.storeId} already exists`); return; } this.stores.set(storeDefinition.storeId, { instance: new storeDefinition.storeClass(), refCount: 0, }); } static getInstance() { return Container.instance; } getStoreDefinition(store) { if ('getStoreDefinition' in store.prototype) { return store.prototype.getStoreDefinition(); } const storeDefinition = (0, utils_1.generateStoreDefinition)(store); Object.assign(store.prototype, { getStoreDefinition: () => storeDefinition, }); return storeDefinition; } get(store) { const storeDefinition = this.getStoreDefinition(store); if (!this.stores.has(storeDefinition.storeId)) { this.instantiate(storeDefinition); } const storeRecord = this.stores.get(storeDefinition.storeId); this.stores.set(storeDefinition.storeId, { ...storeRecord, refCount: storeRecord.refCount + 1, }); return storeRecord.instance; } remove(store) { const storeDefinition = this.getStoreDefinition(store); const storeRecord = this.stores.get(storeDefinition.storeId); if (!storeRecord) { console.warn(`Store record for ${storeDefinition.storeId} does not exist`); return false; } if (storeRecord.refCount > 1) { this.stores.set(storeDefinition.storeId, { ...storeRecord, refCount: storeRecord.refCount - 1, }); return true; } if (storeRecord.instance.destroy) { storeRecord.instance.destroy(); } return this.stores.delete(storeDefinition.storeId); } } exports.Container = Container;