Overview
A LoopBack application has its own life cycles at runtime. There are two methodsto control the transition of states of Application
.
- start(): Start the application
stop(): Stop the applicationIt’s often desirable for various types of artifacts to participate in the lifecycles and perform related processing upon
start
andstop
. Good examples ofsuch artifacts are:Servers
- start: Starts the HTTP server listening for connections.
- stop: Stops the server from accepting new connections.
Components
- A component itself can be a life cycle observer and it can also contributelife cycle observers
DataSources
- connect: Connect to the underlying database or service
- disconnect: Disconnect from the underlying database or service
Custom scripts
- start: Custom logic to be invoked when the application starts
- stop: Custom logic to be invoked when the application stops
The LifeCycleObserver interface
To react on life cycle events, a life cycle observer implements theLifeCycleObserver
interface.
import {ValueOrPromise} from '@loopback/context';
/**
* Observers to handle life cycle start/stop events
*/
export interface LifeCycleObserver {
start?(): ValueOrPromise<void>;
stop?(): ValueOrPromise<void>;
}
Both start
and stop
methods are optional so that an observer can opt incertain events.
Register a life cycle observer
A life cycle observer can be registered by calling lifeCycleObserver()
of theapplication. It binds the observer to the application context with a specialtag - CoreTags.LIFE_CYCLE_OBSERVER
.
app.lifeCycleObserver(MyObserver);
Please note that app.server()
automatically registers servers as life cycleobservers.
Life cycle observers can be registered via a component too:
export class MyComponentWithObservers implements Component {
/**
* Populate `lifeCycleObservers` per `Component` interface to register life
* cycle observers
*/
lifeCycleObservers = [XObserver, YObserver];
}
Discover life cycle observers
The Application
finds all bindings tagged with CoreTags.LIFE_CYCLE_OBSERVER
within the context chain and resolve them as observers to be notified.
Notify life cycle observers of start/stop related events by order
There may be dependencies between life cycle observers and their order ofprocessing for start
and stop
need to be coordinated. For example, weusually start a server to listen on incoming requests only after other parts ofthe application are ready to handle requests. The stop sequence is typicallyprocessed in the reverse order. To support such cases, we introducetwo-dimension steps to control the order of life cycle actions.
Observer groups
First of all, we allow each of the life cycle observers to be tagged with agroup. For example:
datasource (connect/disconnect)
- mongodb
- mysql
server
- rest
- gRPCWe can then configure the application to trigger observers group by group asconfigured by an array of groups in order such as
['datasource', 'server']
.
For example,
app
.bind('observers.MyObserver')
.toClass(MyObserver)
.tag({
[CoreTags.LIFE_CYCLE_OBSERVER_GROUP]: 'g1',
})
.apply(asLifeCycleObserver);
The observer class can also be decorated with @bind
to provide bindingmetadata.
import {bind, createBindingFromClass} from '@loopback/context';
import {CoreTags, asLifeCycleObserver} from '@loopback/core';
@bind(
{
tags: {
[CoreTags.LIFE_CYCLE_OBSERVER_GROUP]: 'g1',
},
},
asLifeCycleObserver,
)
export class MyObserver {
// ...
}
app.add(createBindingFromClass(MyObserver));
Or even simpler with @lifeCycleObserver
:
import {createBindingFromClass} from '@loopback/context';
import {lifeCycleObserver} from '@loopback/core';
@lifeCycleObserver('g1')
export class MyObserver {
// ...
}
app.add(createBindingFromClass(MyObserver));
The order of observers is controlled by a orderedGroups
property ofLifeCycleObserverRegistry
, which receives its options including theorderedGroups
from CoreBindings.LIFE_CYCLE_OBSERVER_OPTIONS
.
export type LifeCycleObserverOptions = {
/**
* Control the order of observer groups for notifications. For example,
* with `['datasource', 'server']`, the observers in `datasource` group are
* notified before those in `server` group during `start`. Please note that
* observers are notified in the reverse order during `stop`.
*/
orderedGroups: string[];
/**
* Notify observers of the same group in parallel, default to `true`
*/
parallel?: boolean;
};
Thus the initial orderedGroups
can be set as follows:
app
.bind(CoreBindings.LIFE_CYCLE_OBSERVER_OPTIONS)
.to({orderedGroups: ['g1', 'g2', 'server']});
Or:
const registry = await app.get(CoreBindings.LIFE_CYCLE_OBSERVER_REGISTRY);
registry.setOrderedGroups(['g1', 'g2', 'server']);
Observers are sorted using orderedGroups
as the relative order. If an observeris tagged with a group that is not defined in orderedGroups
, it will comebefore any groups included in orderedGroups
. Such custom groups are alsosorted by their names alphabetically.
In the example below, orderedGroups
is set to['setup-servers', 'publish-services']
. Given the following observers:
- ‘my-observer-1’ (‘setup-servers’)
- ‘my-observer-2’ (‘publish-services’)
- ‘my-observer-4’ (‘2-custom-group’)
- ‘my-observer-3’ (‘1-custom-group’)The sorted observer groups will be:
{
'1-custom-group': ['my-observer-3'], // by alphabetical order
'2-custom-group': ['my-observer-4'], // by alphabetical order
'setup-servers': ['my-observer-1'], // by orderedGroups
'publish-services': ['my-observer-2'], // orderedGroups
}
The execution order of observers within the same group is controlled byLifeCycleObserverOptions.parallel
:
true
(default): observers within the same group are notified in parallelfalse
: observers within the same group are notified one by one. The order isnot defined. If you want to have one to be invoked before the other, mark themwith two distinct groups.
Add custom life cycle observers by convention
Each application can have custom life cycle observers to be dropped intosrc/observers
folder as classes implementing LifeCycleObserver
.
During application.boot(), such artifacts are discovered, loaded, and bound tothe application context as life cycle observers. This is achieved by a built-inLifeCycleObserverBooter
extension.
CLI command to generate life cycle observers
To make it easy for application developers to add custom life cycle observers,we introduce lb4 observer
command as part the CLI.
$ lb4 observer
? Observer name: test
? Observer group: g1
create src/observers/test.observer.ts
update src/observers/index.ts
Observer test was created in src/observers/
See Life cycle observer generator for moredetails.