-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsonExtender.js
94 lines (79 loc) · 2.7 KB
/
jsonExtender.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
'use strict'
const jsonData = './db.json'
const jsonConcat = require("json-concat");
const Finder = require('fs-finder');
const fsExtra = require('fs-extra');
const requireDir = require('require-dir');
const colors = require('colors');
class jsonExtender {
constructor(options) {
const base = __dirname;
this.generatedPath = options.generatedPath || `${base}/generated`
this.filePath = options.filePath;
this.staticPath =options.staticPath||`${base}/static` ;
this.filesToGenerate = [];
this.startingPoint = null;
this.outputs = [];
this.promise = new Promise((resolve,reject)=>{
this.resolve =resolve;
});
}
register(params) {
if(params instanceof Array ){
this.filesToGenerate.push(...params);
}
else if ( typeof params == 'string' ){
let requires = requireDir(params);
let funcs = Object.keys(requires).map(key => requires[key]) ;
this.filesToGenerate.push(...funcs);
}
}
generate(isRun=true) {
if(!isRun){
return new Promise((resolve,reject)=>{
return resolve({files:'',filePath:`${this.filePath}`});
})
}
return new Promise((resolve,reject)=>{
this.status = 'success';
let prevFunc = this.extend.bind(this);
this.filesToGenerate.reverse().map(func=> {
this.startingPoint = prevFunc = func(prevFunc);
})
this.startingPoint(this.createJson.bind(this));
this.promise.then(data=> resolve(data)).catch((e)=>reject(e));
})
}
createJson(object) {
let absolutePath = `${this.generatedPath}/${object.path}`;
fsExtra.outputJSONSync(absolutePath, object.data, null, (err) => {
console.log(err) // => null
})
}
extend(arr) {
let generatedFiles = Finder.from(`${this.generatedPath}`).findFiles('*.json');
let staticFiles = Finder.from(`${this.staticPath}`).findFiles('*.json');
let files = [...staticFiles,
...generatedFiles]
jsonConcat({
src: [
jsonData,
...files
],
dest: this.filePath
}, (json)=> {
console.log('___________________________________________________________________________________________'.green)
console.log(`finished successfuly`.green)
console.log(`the files created and combined:`.green)
let counter = 1;
files.map((file)=>{
console.log(` ${counter}) ${file}`.green)
counter++;
})
console.log(`the result saved to ${this.filePath} `.green)
console.log('___________________________________________________________________________________________'.green)
this.resolve({files:`${files}`,filePath:`${this.filePath}`});
});
}
}
module.exports = jsonExtender;