lib/src/service/CanonicalInstantiable.ts
garrettmills fcce28081b
All checks were successful
continuous-integration/drone/push Build is passing
AsyncPipe; table schemata; migrations; File logging
2021-07-25 09:15:01 -05:00

33 lines
1.2 KiB
TypeScript

/**
* Error thrown when the item returned from a canonical definition file is not the expected item.
* @extends Error
*/
import {Canonical, CanonicalDefinition} from './Canonical'
import {isInstantiable} from '../di'
/**
* Error thrown when the export of a canonical file is determined to be invalid.
*/
export class InvalidCanonicalExportError extends Error {
constructor(name: string) {
super(`Unable to import canonical item from "${name}". The default export of this file is invalid.`)
}
}
/**
* Variant of the Canonical unit whose files export classes which are instantiated using the global container.
*/
export class CanonicalInstantiable<T> extends Canonical<T> {
public async initCanonicalItem(definition: CanonicalDefinition): Promise<T> {
if ( isInstantiable(definition.imported.default) ) {
return this.app().make(definition.imported.default)
}
if ( isInstantiable(definition.imported[definition.canonicalName.split(':').reverse()[0]]) ) {
return this.app().make(definition.imported[definition.canonicalName.split(':').reverse()[0]])
}
throw new InvalidCanonicalExportError(definition.originalName)
}
}