8

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

Community
  • 1
  • 1
Salitha
  • 1,022
  • 1
  • 12
  • 32

1 Answers1

8

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)...!!!

Salitha
  • 1,022
  • 1
  • 12
  • 32
  • As a service can also have @config options in the constructor, is it possible to change the config params for each request and how? Thank you – Boštjan Pišler Sep 15 '22 at 11:29