I've been trying to wrap my head around providers and decorators in loopback 4 and I have a tough time getting to understand it.
My current implementations look like the following:
export interface MyProviderFn {
(args: any[]): Promise<void>;
}
export class MyActionProvider implements Provider<MyProviderFn> {
public constructor(
@inject(CoreBindings.APPLICATION_INSTANCE)
public app: RestApplication,
@inject.getter(CoreBindings.CONTROLLER_CLASS, { optional: true })
private readonly getController: Getter<Constructor<{}>>,
@inject.getter(CoreBindings.CONTROLLER_METHOD_NAME, { optional: true })
private readonly getMethod: Getter<string>,
) {}
public value(): MyProviderFn {
return args => this.action(args);
}
public async action(args: any[]): Promise<void> {
const controllerClass = await this.getController();
const methodName = await this.getMethod();
if (!controllerClass || !methodName) return;
const metadata = getDecoratorMetadata(controllerClass, methodName);
if (!metadata) {
return;
}
// Provider specific code here
}
}
Is this an accurate way of doing it? Can it be cleaner?
In LoopBack 4, Provider solves the following problem for dependency injection:
binding.to())binding.toDynamicValue())binding.toClass())For example:
class GreetingProvider implements Provider<string> {
// Inject the current language
private constructor(@inject('language') private lang: string) {
}
// Produce resolved value for the binding
value() {
if (this.lang === 'zh') return '你好';
else return 'Hello';
}
}
It can be used in LB4 applications to back any kind of bindings, not limited to actions.
You can find examples in loopback-next repo
Provider has to be a class so that decorators can be applied for dependency injection. Constructor parameters and properties can be decorated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With