UNPKG

@chubbyts/chubbyts-dic

Version:

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

49 lines (48 loc) 1.43 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) => { storedServices.delete(id); storedFactories.set(id, createWrapperFactory(factory, storedFactories.get(id))); }; const get = (id) => { if (!storedServices.has(id)) { 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; };