import container from './container' ; import { IContainerItem } from './types' ; import { Lifecycle } from './lifecycle' ; import { getArgs } from '@brainhubeu/hadron-utils' ; export class ContainerItem implements IContainerItem { constructor ( protected key , protected item ) { } get Item ( ) : any { return this . item ; } set Item ( item ) { this . item = item ; } public getKey ( ) { return this . key ; } public getArgs ( ) { return getArgs ( this . item ) ; } } class ContainerItemSingleton extends ContainerItem { private _itemInstanse : any ; constructor ( key , item ) { super ( key , item ) ; this . _itemInstanse = null ; } set Item ( item ) { this . item = item ; } get Item ( ) : any { const parameters = this . getArgs ( ) ; if ( parameters . length > 0 ) { const parameterInstances = parameters . map ( ( paramName ) => container . take ( paramName ) ) ; if ( this . _itemInstanse === null ) { try { this . _itemInstanse = new this . item ( ... parameterInstances ) ; } catch ( error ) { throw new Error ( `can not create an instance of ${ this . key }` ) ; } } return this . _itemInstanse ; } if ( this . _itemInstanse === null ) { try { this . _itemInstanse = new this . item ( ) ; } catch ( error ) { throw new Error ( `can not create an instance of  ${ this . key }` ) ; } } return this . _itemInstanse ; } } class ContainerItemTransient extends ContainerItem { constructor ( key , item ) { super ( key , item ) ; } set Item ( item ) { this . item = item ; } get Item ( ) : any { const parameters = this . getArgs ( ) ; if ( parameters . length > 0 ) { const parameterInstances = parameters . map ( ( paramName ) => container . take ( paramName ) ) ; try { return new this . item ( ... parameterInstances ) ; } catch ( error ) { throw new Error ( `can not create a new instance of  ${ this . key }` ) ; } } else { try { return new this . item ( ) ; } catch ( error ) { throw new Error ( `can not create a new instance of  ${ this . key }` ) ; } } } } const containerItemFactory = ( key , item , lifecycle ? ) : ContainerItem => { switch ( lifecycle ) { case Lifecycle . Singleton : return new ContainerItemSingleton ( key , item ) ; case Lifecycle . Transient : return new ContainerItemTransient ( key , item ) ; default : return new ContainerItem ( key , item ) ; } } ; export default { containerItemFactory } ;