UNPKG

@chubbyts/chubbyts-dic

Version:

Dependency injection container (DIC), PSR-11 inspired.

48 lines (47 loc) 1.64 kB
const createWrapperFactory = (newFactory, existingFactory) => { return (container) => newFactory(container, existingFactory); }; export const createContainer = () => { const _storedFactories = new Map(); const _storedServices = new Map(); const _create = (id) => { const factoryById = _storedFactories.get(id); if (!factoryById) { throw new Error(`There is no service with id "${id}"`); } try { return factoryById(container); } catch (e) { const error = new Error(`Could not create service with id "${id}"`); // eslint-disable-next-line functional/immutable-data error.cause = e; throw error; } }; const container = { sets: (factories) => { factories.forEach((factory, id) => { container.set(id, factory); }); }, set: (id, factory) => { // eslint-disable-next-line functional/immutable-data _storedServices.delete(id); // eslint-disable-next-line functional/immutable-data _storedFactories.set(id, createWrapperFactory(factory, _storedFactories.get(id))); }, get: (id) => { if (!_storedServices.has(id)) { // eslint-disable-next-line functional/immutable-data _storedServices.set(id, _create(id)); } return _storedServices.get(id); }, has: (id) => _storedFactories.has(id), }; return container; }; export const createParameter = (value) => { return () => value; };