-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.js
105 lines (85 loc) · 2.45 KB
/
load.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const Q = require('queueue');
const logGroup = (cli, group, cb) => {
cli.group(group);
cb();
};
const insertData = (ctrl, data, index) => ctrl.create(data, index).then(res => res.id || res);
const parseJson = function(q, units, filename, cb) {
const cli = units.require('core.cli');
fs.readFile(filename, (err, fileContent) => {
if (err) {
return cb(err);
}
try {
const json = JSON.parse(fileContent);
for (let resource in json) {
const ctrl = units.get(`resources.${resource}.controller`);
if (!ctrl) {
throw new Error(`Error parsing file ${filename}: no resource ${resource} found`);
}
const content = json[resource].reverse();
q.push({
method: logGroup,
args: [ cli, `${resource} << ${content.length} documents from ${filename}` ]
});
content.forEach((data, i) => q.push({
method: insertData,
args: [ ctrl, data, i ]
}));
}
cb();
} catch (e) {
cb(e);
}
});
};
const getFiles = function(dataPath = 'data') {
const root = process.cwd();
const absolutePath = path.resolve(root, dataPath);
return new Promise((resolve, reject) => fs.lstat(absolutePath, (err, stats) => {
if (err) {
return reject(err);
}
if (stats.isFile()) {
return resolve([ absolutePath ]);
}
if (stats.isDirectory()) {
fs.readdir(absolutePath, (err, files) => {
if (err) {
if (err.code === 'ENOENT') {
return reject(new Error(`No ${dataPath} directory found`))
}
return reject(err);
}
const rxJson = /^[^_].*\.json$/;
resolve(files
.filter(name => rxJson.test(name))
.map(name => path.join(absolutePath, name))
);
});
return;
}
reject(new Error(`No ${absolutePath} file or directory found`));
}));
}
module.exports = function(units, dataPath) {
const cli = units.require('core.cli');
return getFiles(dataPath)
.then(files => new Promise(resolve => {
const q = new Q(1)
.on('done', cli.message)
.on('error', cli.error)
.on('drain', resolve);
files.forEach(file => q.push({
method: parseJson,
args: [ q, units, file ]
}));
if (!q.length()) {
resolve('No data files');
}
}));
};