Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use services in Loopback 4

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

like image 508
Salitha Avatar asked Aug 27 '19 13:08

Salitha


1 Answers

Ok, I figured this out myself. I'll explain this in steps that I followed.

  1. 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.

  2. Create binding key withBindingKey.create() method.

export const MY_SERVICE = BindingKey.create<ServiceClass>('service.MyService');

ServiceClass can be either class or interface.

  1. Goto 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...
    ...
}
  1. Inject the service to the class you want. Here I inject to a controller
export class PingdController {
  constructor(
    @inject(MY_SERVICE ) private myService: ServiceClass,
  ) {}
  ...
  ...
}

Now you can access your service like this.myService.getData(someInput)...!!!

like image 136
Salitha Avatar answered Nov 14 '22 05:11

Salitha