-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
110 lines (79 loc) · 2.52 KB
/
index.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
105
106
107
108
109
110
/**
* SailsFactory
*
*/
const _ = require("lodash");
const fs = require("fs");
const path = require("upath");
const Factory = require(path.normalizeSafe("./lib/factory"));
const factoryMap = new Map();
//==============================================================================
class SailsFactory {
constructor(fpath = "") {
const modelName = path.trimExt(path.basename(fpath));
Object.defineProperties(this, {
modelName: { value: modelName }
});
//-- load factory
if (fpath) {
require(fpath)(this);
}
}
//----------------------------------------------------------------------------
load(...args) {
let folder = "test/factories";
let callback = null;
_(args).each((arg) => {
_.isString(arg) && (folder = arg);
_.isFunction(arg) && (callback = arg);
});
const dir = path.resolve(folder);
const files = fs.readdirSync(dir);
let count = 0;
_.forEach(files, (fname) => {
const fpath = path.join(dir, fname);
if (/^[^.].*\.js$/.test(fname) && fs.statSync(fpath).isFile()) {
new SailsFactory(fpath) && ++count;
}
});
callback && callback(count);
}
//----------------------------------------------------------------------------
define(name, modelName) {
const factory = new Factory(name, (modelName || this.modelName || name));
factoryMap.set(name, factory);
return factory;
}
//----------------------------------------------------------------------------
build(name, ...args) {
let attrs = {};
let callback = null;
_(args).each((arg) => {
_.isPlainObject(arg) && (attrs = arg);
_.isFunction(arg) && (callback = arg);
});
const factory = factoryMap.get(name);
if (!factory) {
throw new Error("Factory '" + name + "' is undefined.");
}
return factory.build(attrs, callback);
}
//----------------------------------------------------------------------------
create(name, ...args) {
let attrs = {};
let callback = null;
_(args).each((arg) => {
_.isPlainObject(arg) && (attrs = arg);
_.isFunction(arg) && (callback = arg);
});
const factory = factoryMap.get(name);
if (!factory) {
throw new Error("Factory '" + name + "' is undefined.");
}
return factory.create(attrs, callback);
}
}
//==============================================================================
//-- export
module.exports = new SailsFactory();
//==============================================================================