Overview
LoopBack 4 is designed to be highly extensible. For architectural rationale andmotivation, see Crafting LoopBack 4.
Building blocks for extensibility
The@loopback/contextmodule implements anInversion of Control (IoC)container called Context as a service registry that supportsDependency injection.
The IoC container decouples service providers and consumers. A service providercan be bound to the context with a key, which can be treated as an address ofthe service provider.
The diagram below shows how the Context manages services and their dependencies.
In the example above, there are three services in the Context and each of themare bound to a unique key.
- controllers.UserController: A controller to implement user management APIs
- repositories.UserRepository: A repository to provide persistence for userrecords
- utilities.PasswordHasher: A utility function to hash passwordsPlease also note that
UserController
depends on an instance ofUserRepository
andPasswordHasher
. Such dependencies are also managed by theContext to provide composition capability for service instances.
Service consumers can then either locate the provider using the binding key ordeclare a dependency using @inject('binding-key-of-a-service-provider')
sothat the service provider can be injected into the consumer class. The codesnippet below shows the usage of @inject
for dependency injection.
import {inject, Context} from '@loopback/context';
/**
* A UserController implementation that depends on UserRepository and PasswordHasher
*/
class UserController {
// UserRepository and PasswordHasher are injected via the constructor
constructor(
@inject('repositories.UserRepository') private userRepository: UserRepository,
@inject('utilities.PasswordHasher') private passwordHasher: PasswordHasher),
) {}
/**
* Login a user with name and password
*/
async login(userName: string, password: String): boolean {
const hash = this.passwordHasher.hash(password);
const user = await this.userRepository.findById(userName);
return user && user.passwordHash === hash;
}
}
const ctx = new Context();
// Bind repositories.UserRepository to UserRepository class
ctx.bind('repositories.UserRepository').toClass(MySQLUserRepository);
// Bind utilities.PasswordHash to a function
ctx.bind('utilities.PasswordHash').to(PasswordHasher)
// Bind the UserController class as the user management implementation
ctx.bind('controllers.UserController').toClass(UserController);
// Locate the an instance of UserController from the context
const userController: UserController = await ctx.get<UserController>('controller.UserController');
// Run the login()
const ok = await userController.login('John', 'MyPassWord');
Now you might wonder why the IoC container is fundamental to extensibility.Here’s how it’s achieved.
An alternative implementation of the service provider can be bound thecontext to replace the existing one. For example, we can implement differenthashing functions for password encryption. The user management system canthen receive custom password hashing functions.
Services can be organized as extension points and extensions. For example,to allow multiple authentication strategies, the
authentication
componentcan define an extension point asauthentication-manager
and variousauthentication strategies such as user/password, LDAP, oAuth2 can becontributed to the extension point as extensions. The relation will looklike:
To allow a list of extensions to be contributed to LoopBack framework andapplications, we introduce Component
as the packaging model to bundleextensions. A component is either a npm module or a local folder structure thatcontains one or more extensions. It’s then exported as a class implementing theComponent
interface. For example:
...
import {Component, ProviderMap} from '@loopback/core';
export class UserManagementComponent implements Component {
providers?: ProviderMap;
constructor() {
this.controllers = [UserController];
this.repositories = [UserRepository];
};
}
}
The interaction between the application context and UserManagement
componentis illustrated below:
For more information about components, see:
Types of extensions
- Binding providers
- Decorators
- Sequence Actions
- Connectors
- Utility functions
- Controllers
- Repositories
- Models
- MixinsFor a list of candidate extensions, seeloopback-next issue #512.
System vs Application extensions
Some extensions are meant to extend the programming model and integrationcapability of the LoopBack 4 framework. Good examples of such extensions are:
- Binding providers
- Decorators
- Sequence & Actions
- Connectors
- Utility functions
Mixins (for application)An application may consist of multiple components for the business logic. Forexample, an online shopping application typically has the following component:
UserManagement
- ShoppingCart
- AddressBook
OrderManagementAn application-level component usually contributes:
Controllers
- Repositories
- Models
- Mixins (for models)
How to build my own extensions
Learn from existing ones
Create your own extension
You can scaffold a LoopBack 4 extension project using @loopback/cli
’slb4 extension
command.