Files
lib/src/lifecycle/AppClass.ts

68 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-03-02 18:57:41 -06:00
import {Application} from './Application';
2021-03-08 11:08:56 -06:00
import {Container, DependencyKey} from "@extollo/di";
2021-03-02 18:57:41 -06:00
/**
* Base type for a class that supports binding methods by string.
*/
export interface Bindable {
getBoundMethod(methodName: string): (...args: any[]) => any
}
/**
* Returns true if the given object is bindable.
* @param what
* @return boolean
*/
export function isBindable(what: any): what is Bindable {
return (
what
&& typeof what.getBoundMethod === 'function'
&& what.getBoundMethod.length === 1
&& typeof what.getBoundMethod('getBoundMethod') === 'function'
)
}
2021-03-25 08:50:13 -05:00
/**
* Base for classes that gives access to the global application and container.
*/
2021-03-02 18:57:41 -06:00
export class AppClass {
2021-03-25 08:50:13 -05:00
/** The global application instance. */
2021-03-02 18:57:41 -06:00
private readonly appClassApplication!: Application;
constructor() {
this.appClassApplication = Application.getApplication();
}
2021-03-25 08:50:13 -05:00
/** Get the global Application. */
2021-03-02 18:57:41 -06:00
protected app(): Application {
return this.appClassApplication;
}
2021-03-25 08:50:13 -05:00
/** Get the global Container. */
2021-03-02 18:57:41 -06:00
protected container(): Container {
return this.appClassApplication;
}
2021-03-25 08:50:13 -05:00
/** Call the `make()` method on the global container. */
2021-03-08 11:08:56 -06:00
protected make<T>(target: DependencyKey, ...parameters: any[]): T {
return this.container().make<T>(target, ...parameters)
}
2021-03-02 18:57:41 -06:00
/**
* Get the method with the given name from this class, bound to this class.
* @param {string} methodName
* @return function
*/
public getBoundMethod(methodName: string): (...args: any[]) => any {
// @ts-ignore
if ( typeof this[methodName] !== 'function' ) {
throw new TypeError(`Attempt to get bound method for non-function type: ${methodName}`)
}
return (...args: any[]): any => {
// @ts-ignore
return this[methodName](...args)
}
}
}