UNPKG

@chubbyts/chubbyts-dic

Version:

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

52 lines (51 loc) 1.62 kB
const createWrapperFactory = (newFactory, existingFactory) => { return (container) => newFactory(container, existingFactory); }; export const createContainer = () => { const storedFactories = new Map(); const storedServices = new Map(); const sets = (factories) => { factories.forEach((factory, id) => { set(id, factory); }); }; const 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))); }; const get = (id) => { if (!storedServices.has(id)) { // eslint-disable-next-line functional/immutable-data storedServices.set(id, create(id)); } return storedServices.get(id); }; const has = (id) => storedFactories.has(id); const container = { sets, set, get, has, }; 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; } }; return container; }; export const createParameter = (value) => { return () => value; };