1 10
import glob from "glob";
2 10
import {PlatformTools} from "../platform/PlatformTools";
3 10
import {EntitySchema} from "../index";
4
import {Logger} from "../logger/Logger";
5
/**
6
 * Loads all exported classes from the given directory.
7
 */
8 10
export function importClassesFromDirectories(logger: Logger, directories: string[], formats = [".js", ".cjs", ".ts"]): Function[] {
9

10 10
    const logLevel = "info";
11 10
    const classesNotFoundMessage = "No classes were found using the provided glob pattern: ";
12 10
    const classesFoundMessage = "All classes found using provided glob pattern";
13 10
    function loadFileClasses(exported: any, allLoaded: Function[]) {
14 10
        if (typeof exported === "function" || exported instanceof EntitySchema) {
15 10
            allLoaded.push(exported);
16

17 10
        } else if (Array.isArray(exported)) {
18 10
            exported.forEach((i: any) => loadFileClasses(i, allLoaded));
19

20 10
        } else if (typeof exported === "object" && exported !== null) {
21 10
            Object.keys(exported).forEach(key => loadFileClasses(exported[key], allLoaded));
22

23
        }
24 10
        return allLoaded;
25
    }
26

27 10
    const allFiles = directories.reduce((allDirs, dir) => {
28 10
        return allDirs.concat(glob.sync(PlatformTools.pathNormalize(dir)));
29
    }, [] as string[]);
30

31 10
    if (directories.length > 0 && allFiles.length === 0) {
32 10
        logger.log(logLevel, `${classesNotFoundMessage} "${directories}"`);
33 10
    } else if (allFiles.length > 0) {
34 10
        logger.log(logLevel, `${classesFoundMessage} "${directories}" : "${allFiles}"`);
35
    }
36 10
    const dirs = allFiles
37 10
        .filter(file => {
38 10
            const dtsExtension = file.substring(file.length - 5, file.length);
39 10
            return formats.indexOf(PlatformTools.pathExtname(file)) !== -1 && dtsExtension !== ".d.ts";
40
        })
41 10
        .map(file => require(PlatformTools.pathResolve(file)));
42

43 10
    return loadFileClasses(dirs, []);
44
}
45

46
/**
47
 * Loads all json files from the given directory.
48
 */
49 10
export function importJsonsFromDirectories(directories: string[], format = ".json"): any[] {
50

51 0
    const allFiles = directories.reduce((allDirs, dir) => {
52 0
        return allDirs.concat(glob.sync(PlatformTools.pathNormalize(dir)));
53
    }, [] as string[]);
54

55 0
    return allFiles
56 0
        .filter(file => PlatformTools.pathExtname(file) === format)
57 0
        .map(file => require(PlatformTools.pathResolve(file)));
58
}

Read our documentation on viewing source code .

Loading