UNPKG

2.29 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 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 {config, Constructor, CoreBindings, inject} from '@loopback/core';
7import {
8 ApplicationWithRepositories,
9 ModelMetadataHelper,
10} from '@loopback/repository';
11import debugFactory from 'debug';
12import {BootBindings} from '../keys';
13import {ArtifactOptions, booter} from '../types';
14import {BaseArtifactBooter} from './base-artifact.booter';
15
16const debug = debugFactory('loopback:boot:model-booter');
17
18/**
19 * A class that extends BaseArtifactBooter to boot the 'Model' artifact type.
20 *
21 * Supported phases: configure, discover, load
22 *
23 * @param app - Application instance
24 * @param projectRoot - Root of User Project relative to which all paths are resolved
25 * @param bootConfig - Model Artifact Options Object
26 */
27@booter('models')
28export class ModelBooter extends BaseArtifactBooter {
29 constructor(
30 @inject(CoreBindings.APPLICATION_INSTANCE)
31 public app: ApplicationWithRepositories,
32 @inject(BootBindings.PROJECT_ROOT) projectRoot: string,
33 @config()
34 public modelConfig: ArtifactOptions = {},
35 ) {
36 super(
37 projectRoot,
38 // Set Model Booter Options if passed in via bootConfig
39 Object.assign({}, ModelDefaults, modelConfig),
40 );
41 }
42
43 /**
44 * Uses super method to get a list of Artifact classes. Boot each file by
45 * creating a DataSourceConstructor and binding it to the application class.
46 */
47 async load() {
48 await super.load();
49
50 for (const cls of this.classes) {
51 if (!isModelClass(cls)) {
52 debug('Skipping class %s - no @model is found', cls.name);
53 continue;
54 }
55
56 debug('Bind class: %s', cls.name);
57 // We are binding the model class itself
58 const binding = this.app.model(cls);
59 debug('Binding created for model class %s: %j', cls.name, binding);
60 }
61 }
62}
63
64/**
65 * Default ArtifactOptions for DataSourceBooter.
66 */
67export const ModelDefaults: ArtifactOptions = {
68 dirs: ['models'],
69 extensions: ['.model.js'],
70 nested: true,
71};
72
73function isModelClass(cls: Constructor<unknown>) {
74 return ModelMetadataHelper.getModelMetadata(cls) != null;
75}