In Abstract
How to use Loopback 4 service generator and create local service class to handle data outside the *.repository or *.controller
In Detail
I'm developing a system that requires external APIs to fetch data, complex hashing/encryption etc. that does not fall into controller scope or repository scope (for the sake of clean code). Loopback 4 has CLI command lb4 service to generate service and this is poorly documented. How to create a class inside the /service folder and import (or inject or bind or whatever) and use it's methods as we do with repositories?
ex:
call methods from service like this.PasswordService.encrypt('some text')
or
this.TwitterApiService.getTweets() that are defined in /service directory
Ok, I figured this out myself. I'll explain this in steps that I followed.
create folder /src/service and inside it create myService.service.ts and index.ts as same as in controller,repository etc. (or use lb4 service and select local service class). note: If you want to implement interface, you can.
Create binding key withBindingKey.create() method.
export const MY_SERVICE = BindingKey.create<ServiceClass>('service.MyService');
ServiceClass can be either class or interface.
application.ts and bind the key (here service.MyService) to the service class.export class NoboBackend extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    super(options);
    ...
    //add below line
    this.bind('service.MyService').toClass(ServiceClass);
    //and code goes on...
    ...
}
export class PingdController {
  constructor(
    @inject(MY_SERVICE ) private myService: ServiceClass,
  ) {}
  ...
  ...
}
Now you can access your service like this.myService.getData(someInput)...!!!
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