You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/src/service/CanonicalInstantiable.ts

33 lines
1.2 KiB

3 years ago
/**
* 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'
3 years ago
/**
* Error thrown when the export of a canonical file is determined to be invalid.
*/
3 years ago
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> {
3 years ago
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]])
}
3 years ago
throw new InvalidCanonicalExportError(definition.originalName)
}
}