import { getDependencyByIndex , IdentifierUndefinedError , setDependency } from './decorators' ; import { DependencyIdentifier } from './dependencyIdentifier' ; import { Ctor , prettyPrintIdentifier } from './dependencyItem' ; import { RediError } from './error' ; import { Quantity } from './types' ; class QuantityCheckError extends RediError { constructor ( id , quantity , actual ) { const msg = `Expect "${ quantity }" dependency items for id "${ prettyPrintIdentifier ( id ) }" but get ${ actual }.` ; super ( msg ) ; } } export function checkQuantity ( id , quantity , length ) { if ( ( quantity === Quantity . OPTIONAL && length > 1 ) || ( quantity === Quantity . REQUIRED && length !== 1 ) ) { throw new QuantityCheckError ( id , quantity , length ) ; } } export function retrieveQuantity < T > ( quantity , arr ) { if ( quantity === Quantity . MANY ) { return arr ; } else { return arr [ 0 ] ; } } function changeQuantity ( target , index , quantity ) { const descriptor = getDependencyByIndex ( target , index ) ; descriptor . quantity = quantity ; } function quantifyDecoratorFactoryProducer ( quantity ) { return function decoratorFactory < T > ( this , id ? ) { if ( this instanceof decoratorFactory ) { return this ; } return function ( registerTarget , _key , index ) { if ( id ) { setDependency ( registerTarget , id , index , quantity ) ; } else { if ( quantity === Quantity . REQUIRED ) { throw new IdentifierUndefinedError ( registerTarget , index ) ; } changeQuantity ( registerTarget , index , quantity ) ; } } ; } as any ; } interface ManyDecorator { ( id ? ) : any ; new ( ) : ManyDecorator ; } export const Many = quantifyDecoratorFactoryProducer ( Quantity . MANY ) ; interface OptionalDecorator { ( id ? ) : any ; new ( ) : OptionalDecorator ; } export const Optional = quantifyDecoratorFactoryProducer ( Quantity . OPTIONAL ) ; interface InjectDecorator { ( id ) : any ; new ( ) : InjectDecorator ; } export const Inject = quantifyDecoratorFactoryProducer ( Quantity . REQUIRED ) ;