UNPKG

2.28 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/boot
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import {
7 Application,
8 config,
9 Constructor,
10 CoreBindings,
11 inject,
12 isLifeCycleObserverClass,
13 LifeCycleObserver,
14} from '@loopback/core';
15import debugFactory from 'debug';
16import {BootBindings} from '../keys';
17import {ArtifactOptions, booter} from '../types';
18import {BaseArtifactBooter} from './base-artifact.booter';
19
20const debug = debugFactory('loopback:boot:lifecycle-observer-booter');
21
22type LifeCycleObserverClass = Constructor<LifeCycleObserver>;
23
24/**
25 * A class that extends BaseArtifactBooter to boot the 'LifeCycleObserver' artifact type.
26 *
27 * Supported phases: configure, discover, load
28 *
29 * @param app - Application instance
30 * @param projectRoot - Root of User Project relative to which all paths are resolved
31 * @param bootConfig - LifeCycleObserver Artifact Options Object
32 */
33@booter('observers')
34export class LifeCycleObserverBooter extends BaseArtifactBooter {
35 observers: LifeCycleObserverClass[];
36
37 constructor(
38 @inject(CoreBindings.APPLICATION_INSTANCE)
39 public app: Application,
40 @inject(BootBindings.PROJECT_ROOT) projectRoot: string,
41 @config()
42 public observerConfig: ArtifactOptions = {},
43 ) {
44 super(
45 projectRoot,
46 // Set LifeCycleObserver Booter Options if passed in via bootConfig
47 Object.assign({}, LifeCycleObserverDefaults, observerConfig),
48 );
49 }
50
51 /**
52 * Uses super method to get a list of Artifact classes. Boot each file by
53 * creating a DataSourceConstructor and binding it to the application class.
54 */
55 async load() {
56 await super.load();
57
58 this.observers = this.classes.filter(isLifeCycleObserverClass);
59 for (const observer of this.observers) {
60 debug('Bind life cycle observer: %s', observer.name);
61 const binding = this.app.lifeCycleObserver(observer);
62 debug('Binding created for life cycle observer: %j', binding);
63 }
64 }
65}
66
67/**
68 * Default ArtifactOptions for DataSourceBooter.
69 */
70export const LifeCycleObserverDefaults: ArtifactOptions = {
71 dirs: ['observers'],
72 extensions: ['.observer.js'],
73 nested: true,
74};