Loopback-next: Adding application logic

Created on 27 Jun 2019  路  6Comments  路  Source: strongloop/loopback-next

I couldn't find best place to add application logic.

I want to add scheduler in my application which can be accessed from remote methods to get status. With this answer on SO https://stackoverflow.com/questions/55569988/loopback-4-scheduled-cron-example-using-loopback-4 I managed to do it. But Now I have to place my business logic in LB3 I was using BootScripts and Services for this. In LB4 services are not possible as they need datasource.

I have made a class but failing to access it in controller. below is the code of it
````
import {bind, BindingScope} from '@loopback/context';

@bind({
scope: BindingScope.SINGLETON,
tags: ['bll'],
})
export class PatientRegistrationClass{
constructor() {}

sample(){
    console.log('loading class')
}

}

````

injecting with below statement in PatientVisitController
@inject('bll') private patientRegistration: PatientRegistrationClass

question

All 6 comments

  1. Please check out https://loopback.io/doc/en/lb4/Life-cycle.html

  2. Add @bind to a class does not bind it to context automatically. The purpose of @bind is to customize how it is bound. See https://loopback.io/doc/en/lb4/Binding.html#configure-binding-attributes-for-a-class.

  3. @inject('bll') is to inject a dependency by key, not tags.

I have made couple of changes..
In application.ts
this.bind('patient-registration').toClass(PatientRegistrationClass)
In PatientVisitController
@inject('patient-registration') private patientRegistration: PatientRegistrationClass

It is working but I am not sure if it Is the right way.

If I have multiple classes lets say 10, Do I have to bind them one by one?

Yes, unless you add a booter to do it automatically. See https://loopback.io/doc/en/lb4/Booting-an-Application.html#custom-booters.

I was thinking of booter for scheduler too.. but there isn't any good example on how to make one, bind in app context and which phase to; use out of discover or load...

have seen this https://stackoverflow.com/questions/54959679/loopback-4-access-a-service-in-a-custom-booter so far..

For schedulers, please use life cycle observer - https://loopback.io/doc/en/lb4/Life-cycle.html. They are automatically booted.

Was this page helpful?
0 / 5 - 0 ratings