/
load-files.ts
49 lines (40 loc) 路 1.37 KB
/
load-files.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import path from 'path';
import _ from 'lodash';
import fse from 'fs-extra';
import { importDefault } from '@strapi/utils';
import { glob } from 'glob';
import filePathToPath from './filepath-to-prop-path';
/**
* Returns an Object build from a list of files matching a glob pattern in a directory
* It builds a tree structure resembling the folder structure in dir
*/
export default async function loadFiles<T extends object>(
dir: string,
pattern: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
{ requireFn = importDefault, shouldUseFileNameAsKey = (_: any) => true, globArgs = {} } = {}
): Promise<T> {
const root = {};
const files = await glob(pattern, { cwd: dir, ...globArgs });
for (const file of files) {
const absolutePath = path.resolve(dir, file);
// load module
delete require.cache[absolutePath];
let mod;
if (path.extname(absolutePath) === '.json') {
mod = await fse.readJson(absolutePath);
} else {
mod = requireFn(absolutePath);
}
Object.defineProperty(mod, '__filename__', {
enumerable: true,
configurable: false,
writable: false,
value: path.basename(file),
});
const propPath = filePathToPath(file, shouldUseFileNameAsKey(file));
if (propPath.length === 0) _.merge(root, mod);
_.merge(root, _.setWith({}, propPath, mod, Object));
}
return root as T;
}