1 | ;
|
2 | // Copyright IBM Corp. and LoopBack contributors 2018,2019. All Rights Reserved.
|
3 | // Node module: @loopback/boot
|
4 | // This file is licensed under the MIT License.
|
5 | // License text available at https://opensource.org/licenses/MIT
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | exports.loadClassesFromFiles = exports.isClass = exports.discoverFiles = void 0;
|
8 | const tslib_1 = require("tslib");
|
9 | const debug_1 = tslib_1.__importDefault(require("debug"));
|
10 | const path_1 = tslib_1.__importDefault(require("path"));
|
11 | const glob_1 = require("glob");
|
12 | const debug = (0, debug_1.default)('loopback:boot:booter-utils');
|
13 | /**
|
14 | * Returns all files matching the given glob pattern relative to root
|
15 | *
|
16 | * @param pattern - A glob pattern
|
17 | * @param root - Root folder to start searching for matching files
|
18 | * @returns Array of discovered files
|
19 | */
|
20 | async function discoverFiles(pattern, root) {
|
21 | return (0, glob_1.glob)(pattern, { root: root });
|
22 | }
|
23 | exports.discoverFiles = discoverFiles;
|
24 | /**
|
25 | * Given a function, returns true if it is a class, false otherwise.
|
26 | *
|
27 | * @param target - The function to check if it's a class or not.
|
28 | * @returns True if target is a class. False otherwise.
|
29 | */
|
30 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
31 | function isClass(target) {
|
32 | return (typeof target === 'function' && target.toString().indexOf('class') === 0);
|
33 | }
|
34 | exports.isClass = isClass;
|
35 | /**
|
36 | * Returns an Array of Classes from given files. Works by requiring the file,
|
37 | * identifying the exports from the file by getting the keys of the file
|
38 | * and then testing each exported member to see if it's a class or not.
|
39 | *
|
40 | * @param files - An array of string of absolute file paths
|
41 | * @param projectRootDir - The project root directory
|
42 | * @returns An array of Class constructors from a file
|
43 | */
|
44 | function loadClassesFromFiles(files, projectRootDir) {
|
45 | const classes = [];
|
46 | for (const file of files) {
|
47 | debug('Loading artifact file %j', path_1.default.relative(projectRootDir, file));
|
48 | const moduleObj = require(file);
|
49 | for (const k in moduleObj) {
|
50 | const exported = moduleObj[k];
|
51 | if (isClass(exported)) {
|
52 | debug(' add %s (class %s)', k, exported.name);
|
53 | classes.push(exported);
|
54 | }
|
55 | else {
|
56 | debug(' skip non-class %s', k);
|
57 | }
|
58 | }
|
59 | }
|
60 | return classes;
|
61 | }
|
62 | exports.loadClassesFromFiles = loadClassesFromFiles;
|
63 | //# sourceMappingURL=booter-utils.js.map |
\ | No newline at end of file |