lib/src/lifecycle/AppClass.ts

65 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-06-03 03:36:25 +00:00
import {Application} from './Application'
import {Container, Injectable, TypedDependencyKey} from '../di'
2021-03-03 00:57:41 +00: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
*/
2021-06-03 03:36:25 +00:00
export function isBindable(what: unknown): what is Bindable {
2021-03-03 00:57:41 +00:00
return (
2021-06-03 03:36:25 +00:00
Boolean(what)
&& typeof (what as any).getBoundMethod === 'function'
&& (what as any).getBoundMethod.length === 1
&& typeof (what as any).getBoundMethod('getBoundMethod') === 'function'
2021-03-03 00:57:41 +00:00
)
}
2021-03-25 13:50:13 +00:00
/**
* Base for classes that gives access to the global application and container.
*/
@Injectable()
2021-03-03 00:57:41 +00:00
export class AppClass {
2021-03-25 13:50:13 +00:00
/** The global application instance. */
private get appClassApplication(): Application {
return Application.getApplication()
2021-03-03 00:57:41 +00:00
}
2021-03-25 13:50:13 +00:00
/** Get the global Application. */
2021-03-03 00:57:41 +00:00
protected app(): Application {
2021-06-03 03:36:25 +00:00
return this.appClassApplication
2021-03-03 00:57:41 +00:00
}
2021-03-25 13:50:13 +00:00
/** Get the global Container. */
2021-03-03 00:57:41 +00:00
protected container(): Container {
2021-06-03 03:36:25 +00:00
return this.appClassApplication
2021-03-03 00:57:41 +00:00
}
2021-03-25 13:50:13 +00:00
/** Call the `make()` method on the global container. */
protected make<T>(target: TypedDependencyKey<T>, ...parameters: any[]): T {
2021-03-08 17:08:56 +00:00
return this.container().make<T>(target, ...parameters)
}
2021-03-03 00:57:41 +00: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 {
2021-06-03 03:36:25 +00:00
if ( typeof (this as any)[methodName] !== 'function' ) {
2021-03-03 00:57:41 +00:00
throw new TypeError(`Attempt to get bound method for non-function type: ${methodName}`)
}
return (...args: any[]): any => {
2021-06-03 03:36:25 +00:00
return (this as any)[methodName](...args)
2021-03-03 00:57:41 +00:00
}
}
}