As explained in Using Components, a typical LoopBackcomponent is an npm package exporting a Component class.

  1. import {MyController} from './controllers/my.controller';
  2. import {MyValueProvider} from './providers/my-value.provider';
  3. import {Component} from '@loopback/core';
  4. export class MyComponent implements Component {
  5. servers = {
  6. 'my-server': MyServer,
  7. };
  8. lifeCycleObservers = [MyObserver];
  9. controllers = [MyController];
  10. providers = {
  11. 'my-value': MyValueProvider,
  12. };
  13. classes = {
  14. 'my-validator': MyValidator,
  15. };
  16. constructor() {
  17. // Set up `bindings`
  18. const bindingX = Binding.bind('x').to('Value X');
  19. const bindingY = Binding.bind('y').toClass(ClassY);
  20. this.bindings = [bindingX, bindingY];
  21. }
  22. }

You can inject anything from the context and access them from a component. Inthe following example, the REST application instance is made available in thecomponent via dependency injection.

  1. import {inject, Component, CoreBindings} from '@loopback/core';
  2. import {RestApplication} from '@loopback/rest';
  3. export class MyComponent implements Component {
  4. constructor(
  5. @inject(CoreBindings.APPLICATION_INSTANCE)
  6. private application: RestApplication,
  7. ) {
  8. // The rest application instance can be accessed from this component
  9. }
  10. }

When a component is mounted to an application, a new instance of the componentclass is created and then:

  • Each Controller class is registered via app.controller(),
  • Each Provider is bound to its key in providers object viaapp.bind(key).toProvider(providerClass)
  • Each Class is bound to its key in classes object viaapp.bind(key).toClass(cls)
  • Each Binding is added via app.add(binding)
  • Each Server class is registered via app.server()
  • Each LifeCycleObserver class is registered via app.lifeCycleObserver()Please note that providers and classes are shortcuts for provider and classbindings.

The example MyComponent above will add MyController to application’s API andcreate the following bindings in the application context:

  • my-value -> MyValueProvider (provider)
  • my-validator -> MyValidator (class)
  • x -> 'Value X' (value)
  • y -> ClassY (class)
  • my-server -> MyServer (server)
  • lifeCycleObservers.MyObserver -> MyObserver (life cycle observer)

Providers

Providers enable components to export values that can be used by the targetapplication or other components. The Provider class provides a value()function called by Context when another entity requests a value tobe injected.

  1. import {Provider} from '@loopback/context';
  2. export class MyValueProvider implements Provider<string> {
  3. value() {
  4. return 'Hello world';
  5. }
  6. }

Specifying binding key

Notice that the provider class itself does not specify any binding key, the keyis assigned by the component class.

  1. import {MyValueProvider} from './providers/my-value.provider';
  2. export class MyComponent implements Component {
  3. constructor() {
  4. this.providers = {
  5. 'my-component.my-value': MyValueProvider,
  6. };
  7. }
  8. }

We recommend to component authors to useTyped binding keys insteadof string keys and to export an object (a TypeScript namespace) providingconstants for all binding keys defined by the component.

  1. import {MyValue, MyValueProvider} from './providers/my-value-provider';
  2. export namespace MyComponentKeys {
  3. export const MY_VALUE = new BindingKey<MyValue>('my-component.my-value');
  4. }
  5. export class MyComponent implements Component {
  6. constructor() {
  7. this.providers = {
  8. [MyComponentKeys.MY_VALUE.key]: MyValueProvider,
  9. };
  10. }
  11. }

Accessing values from Providers

Applications can use @inject decorators to access the value of an exportedProvider. If you’re not familiar with decorators in TypeScript, seeKey Concepts: Decorators

  1. const app = new Application();
  2. app.component(MyComponent);
  3. class MyController {
  4. constructor(@inject('my-component.my-value') private greeting: string) {}
  5. @get('/greet')
  6. greet() {
  7. return this.greeting;
  8. }
  9. }

A note on binding names

To avoid name conflicts, add a unique prefix to your binding key (for example, my-component.in the example above). See Reserved binding keys forthe list of keys reserved for the framework use.

Asynchronous providers

Provider’s value() method can be asynchronous too:

  1. import {Provider} from '@loopback/context';
  2. const request = require('request-promise-native');
  3. const weatherUrl =
  4. 'http://samples.openweathermap.org/data/2.5/weather?appid=b1b15e88fa797225412429c1c50c122a1';
  5. export class CurrentTemperatureProvider implements Provider<number> {
  6. async value() {
  7. const data = await request(`${weatherUrl}&q=Prague,CZ`, {json: true});
  8. return data.main.temp;
  9. }
  10. }

In this case, LoopBack will wait until the promise returned by value() isresolved, and use the resolved value for dependency injection.

Working with HTTP request/response

In some cases, the Provider may depend on other parts of LoopBack; for examplethe current request object. The Provider’s constructor should list suchdependencies annotated with @inject keyword, so that LoopBack runtime canresolve them automatically.

  1. import {Provider} from '@loopback/context';
  2. import {Request, RestBindings} from '@loopback/rest';
  3. const uuid = require('uuid/v4');
  4. class CorrelationIdProvider implements Provider<string> {
  5. constructor(@inject(RestBindings.Http.REQUEST) private request: Request) {}
  6. value() {
  7. return this.request.headers['X-Correlation-Id'] || uuid();
  8. }
  9. }

Modifying request handling logic

A frequent use case for components is to modify the way requests are handled.For example, the authentication component needs to verify user credentialsbefore the actual handler can be invoked; or a logger component needs to recordstart time and write a log entry when the request has been handled.

The idiomatic solution has two parts:

  • The component should define and bind a newSequence action, for exampleauthentication.actions.authenticate:
  1. import {Component} from '@loopback/core';
  2. export namespace AuthenticationBindings {
  3. export const AUTH_ACTION = BindingKey.create<AuthenticateFn>(
  4. 'authentication.actions.authenticate',
  5. );
  6. }
  7. class AuthenticationComponent implements Component {
  8. constructor() {
  9. this.providers = {
  10. [AuthenticationBindings.AUTH_ACTION.key]: AuthenticateActionProvider,
  11. };
  12. }
  13. }

A sequence action is typically implemented as an action() method in theprovider.

  1. class AuthenticateActionProvider implements Provider<AuthenticateFn> {
  2. // Provider interface
  3. value() {
  4. return request => this.action(request);
  5. }
  6. // The sequence action
  7. action(request): UserProfile | undefined {
  8. // authenticate the user
  9. }
  10. }

It may be tempting to put action implementation directly inside theanonymous arrow function returned by provider’s value() method. Weconsider that as a bad practice though, because when an error occurs, thestack trace will contain only an anonymous function that makes it moredifficult to link the entry with the sequence action.

  • The application should use a custom Sequence class which calls this newsequence action in an appropriate place.
  1. class AppSequence implements SequenceHandler {
  2. constructor(
  3. @inject(RestBindings.SequenceActions.FIND_ROUTE)
  4. protected findRoute: FindRoute,
  5. @inject(RestBindings.SequenceActions.PARSE_PARAMS)
  6. protected parseParams: ParseParams,
  7. @inject(RestBindings.SequenceActions.INVOKE_METHOD)
  8. protected invoke: InvokeMethod,
  9. @inject(RestBindings.SequenceActions.SEND) public send: Send,
  10. @inject(RestBindings.SequenceActions.REJECT) public reject: Reject,
  11. // Inject the new action here:
  12. @inject('authentication.actions.authenticate')
  13. protected authenticate: AuthenticateFn,
  14. ) {}
  15. async handle(context: RequestContext) {
  16. try {
  17. const {request, response} = context;
  18. const route = this.findRoute(request);
  19. // Invoke the new action:
  20. const user = await this.authenticate(request);
  21. const args = await parseOperationArgs(request, route);
  22. const result = await this.invoke(route, args);
  23. this.send(response, result);
  24. } catch (error) {
  25. this.reject(context, err);
  26. }
  27. }
  28. }

Accessing Elements contributed by other Sequence Actions

When writing a custom sequence action, you need to access Elements contributedby other actions run in the sequence. For example, authenticate() action needsinformation about the invoked route to decide whether and how to authenticatethe request.

Because all Actions are resolved before the Sequence handle function is run,Elements contributed by Actions are not available for injection yet. To solvethis problem, use @inject.getter decorator to obtain a getter function insteadof the actual value. This allows you to defer resolution of your dependency onlyuntil the sequence action contributing this value has already finished.

  1. export class AuthenticateActionProvider implements Provider<AuthenticateFn> {
  2. constructor(
  3. @inject.getter(BindingKeys.Authentication.STRATEGY) readonly getStrategy,
  4. ) {}
  5. value() {
  6. return request => this.action(request);
  7. }
  8. async action(request): Promise<UserProfile | undefined> {
  9. const strategy = await this.getStrategy();
  10. // ...
  11. }
  12. }

Contributing Elements from Sequence Actions

Use @inject.setter decorator to obtain a setter function that can be used tocontribute new Elements to the request context.

  1. export class AuthenticateActionProvider implements Provider<AuthenticateFn> {
  2. constructor(
  3. @inject.getter(BindingKeys.Authentication.STRATEGY) readonly getStrategy,
  4. @inject.setter(BindingKeys.Authentication.CURRENT_USER)
  5. readonly setCurrentUser,
  6. ) {}
  7. value() {
  8. return request => this.action(request);
  9. }
  10. async action(request): UserProfile | undefined {
  11. const strategy = await this.getStrategy();
  12. // (authenticate the request using the obtained strategy)
  13. const user = this.setCurrentUser(user);
  14. return user;
  15. }
  16. }

Extending Application with Mixins

When binding a component to an app, you may want to extend the app with thecomponent’s properties and methods by using mixins.

An example of how a mixin leverages a component is RepositoryMixin. Suppose anapp has multiple components with repositories bound to each of them. You can usefunction RepositoryMixin() to mount those repositories to application levelcontext.

The following snippet is an abbreviated functionRepositoryMixin:

src/mixins/repository.mixin.ts

  1. export function RepositoryMixin<T extends Class<any>>(superClass: T) {
  2. return class extends superClass {
  3. constructor(...args: any[]) {
  4. super(...args);
  5. }
  6. }
  7. /**
  8. * Add a component to this application. Also mounts
  9. * all the components' repositories.
  10. */
  11. public component(component: Class<any>) {
  12. super.component(component);
  13. this.mountComponentRepository(component);
  14. }
  15. mountComponentRepository(component: Class<any>) {
  16. const componentKey = `components.${component.name}`;
  17. const compInstance = this.getSync(componentKey);
  18. // register a component's repositories in the app
  19. if (compInstance.repositories) {
  20. for (const repo of compInstance.repositories) {
  21. this.repository(repo);
  22. }
  23. }
  24. }
  25. }

Then you can extend the app with repositories in a component:

index.ts

  1. import {RepositoryMixin} from 'src/mixins/repository.mixin';
  2. import {Application} from '@loopback/core';
  3. import {FooComponent} from 'src/foo.component';
  4. class AppWithRepoMixin extends RepositoryMixin(Application) {}
  5. let app = new AppWithRepoMixin();
  6. app.component(FooComponent);
  7. // `app.find` returns all repositories in FooComponent
  8. app.find('repositories.*');

Configuring components

More often than not, the component may want to offer different value providersdepending on the configuration. For example, a component providing an email APImay offer different transports (stub, SMTP, and so on).

Components should use constructor-levelDependency Injection to receive theconfiguration from the application.

  1. class EmailComponent {
  2. constructor(@inject('config#components.email') config) {
  3. this.providers = {
  4. sendEmail:
  5. this.config.transport == 'stub'
  6. ? StubTransportProvider
  7. : SmtpTransportProvider,
  8. };
  9. }
  10. }