-
Notifications
You must be signed in to change notification settings - Fork 406
/
data_loader.js
73 lines (62 loc) · 1.9 KB
/
data_loader.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
const glob = require('glob'),
_ = require('lodash'),
path = require('path'),
yaml = require('js-yaml');
/**
* Loads a single config file, in yaml/json format.
*
* @param dataFilePath - leave off the file extension.
* @param fsDep
* @returns {*}
*/
function loadFile(dataFilePath, fsDep) {
const dataFilesFullPath = `${dataFilePath}.{json,yml,yaml}`;
if (dataFilePath) {
const dataFiles = glob.sync(dataFilesFullPath),
dataFile = _.head(dataFiles);
if (dataFile && fsDep.existsSync(path.resolve(dataFile))) {
try {
return yaml.load(fsDep.readFileSync(path.resolve(dataFile), 'utf8'));
} catch (err) {
throw new Error(`Error loading file: ${dataFile} - ${err.message}`);
}
}
}
return null;
}
/**
* Loads a set of config files from a folder, in yaml/json format.
*
* @param dataFilesPath - leave off the file extension
* @param excludeFileNames - leave off the file extension
* @param fsDep
* @returns Object, with merged data files, empty object if no files.
*/
function loadDataFromFolder(dataFilesPath, excludeFileNames, fsDep) {
const dataFilesFullPath = dataFilesPath + '*.{json,yml,yaml}',
excludeFullPath = dataFilesPath + excludeFileNames + '.{json,yml,yaml}';
const globOptions = {};
if (excludeFileNames) {
globOptions.ignore = [excludeFullPath];
}
const dataFiles = glob.sync(dataFilesFullPath, globOptions);
let mergeObject = {};
dataFiles.forEach(function (filePath) {
try {
const jsonData = yaml.load(
fsDep.readFileSync(path.resolve(filePath), 'utf8')
);
mergeObject = _.merge(mergeObject, jsonData);
} catch (err) {
throw new Error(`Error loading file: ${filePath} - ${err.message}`);
}
});
return mergeObject;
}
module.exports = function configFileLoader() {
return {
loadDataFromFile: loadFile,
loadDataFromFolder: loadDataFromFolder,
};
};