UNPKG

2.43 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 {config, CoreBindings, inject} from '@loopback/core';
7import {
8 ApplicationWithRepositories,
9 Class,
10 juggler,
11} from '@loopback/repository';
12import {BootBindings} from '../keys';
13import {ArtifactOptions, booter} from '../types';
14import {BaseArtifactBooter} from './base-artifact.booter';
15
16/**
17 * A class that extends BaseArtifactBooter to boot the 'DataSource' artifact type.
18 * Discovered DataSources are bound using `app.dataSource()`.
19 *
20 * Supported phases: configure, discover, load
21 *
22 * @param app - Application instance
23 * @param projectRoot - Root of User Project relative to which all paths are resolved
24 * @param bootConfig - DataSource Artifact Options Object
25 */
26@booter('datasources')
27export class DataSourceBooter extends BaseArtifactBooter {
28 constructor(
29 @inject(CoreBindings.APPLICATION_INSTANCE)
30 public app: ApplicationWithRepositories,
31 @inject(BootBindings.PROJECT_ROOT) projectRoot: string,
32 @config()
33 public datasourceConfig: ArtifactOptions = {},
34 ) {
35 super(
36 projectRoot,
37 // Set DataSource Booter Options if passed in via bootConfig
38 Object.assign({}, DataSourceDefaults, datasourceConfig),
39 );
40 }
41
42 /**
43 * Uses super method to get a list of Artifact classes. Boot each file by
44 * creating a DataSourceConstructor and binding it to the application class.
45 */
46 async load() {
47 await super.load();
48
49 /**
50 * If DataSource Classes were discovered, we need to make sure RepositoryMixin
51 * was used (so we have `app.dataSource()`) to perform the binding of a
52 * DataSource Class.
53 */
54 if (this.classes.length > 0) {
55 if (!this.app.dataSource) {
56 console.warn(
57 'app.dataSource() function is needed for DataSourceBooter. You can add ' +
58 'it to your Application using RepositoryMixin from @loopback/repository.',
59 );
60 } else {
61 this.classes.forEach(cls => {
62 this.app.dataSource(cls as Class<juggler.DataSource>);
63 });
64 }
65 }
66 }
67}
68
69/**
70 * Default ArtifactOptions for DataSourceBooter.
71 */
72export const DataSourceDefaults: ArtifactOptions = {
73 dirs: ['datasources'],
74 extensions: ['.datasource.js'],
75 nested: true,
76};