/
seed.js
193 lines (167 loc) · 4.96 KB
/
seed.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
'use strict';
var debug = require('debug')('slu:tools:seed');
var async = require('async');
var path = require('path');
var fs = require('fs-extra');
var Module = require('module');
module.exports = function (app, action, options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
if (typeof options === 'string') {
options = {seeds: options};
}
options = options || {};
var seed = new Seed(app);
seed.once('complete', callback || function () {
process.exit();
});
var root = app.root || process.cwd();
var seedsDir = options.seeds;
if (!seedsDir) {
seedsDir = path.join(root, '/db/seeds/');
if (!fs.existsSync(seedsDir)) {
seedsDir = path.join(root, '/server/db/seeds/');
}
if (!fs.existsSync(seedsDir)) {
console.error('Can not find seeds path from: \n1) `seeds` env variable; \n2) [root]/db/seeds; \n3) [root]/server/db/seeds');
throw new Error('Can not find seeds path');
}
}
var seedPath = path.join(seedsDir, app.get('env'));
switch (action) {
default:
case 'plant':
case 'read':
seed.plant(app, seedPath);
break;
case 'harvest':
case 'write':
seed.harvest(app, seedPath);
break;
}
};
function eachModels(app, fn) {
var loopback = app.loopback;
var models = loopback.modelBuilder.models;
for (var name in models) if (models.hasOwnProperty(name)) {
if (['Model', 'PersistedModel'].indexOf(name) >= 0) continue;
if (name.indexOf('AnonymousModel') === 0) continue;
fn(models[name], name);
}
}
function Seed(app) {
var that = this;
var queue = [];
eachModels(app, function (Model) {
Model.seed = getSeedMethod(Model);
});
function getSeedMethod(Model) {
return function seedMethod(seed) {
if (queue.length === 0) process.nextTick(next);
queue.push({Model: Model, seed: seed});
};
}
function next() {
var task = queue.shift();
if (!task) return that.emit('complete');
var Model = task.Model;
var data = typeof task.seed === 'function' ? task.seed() : task.seed;
if (Model.dataSource) {
_seed(Model, data, next);
} else {
Model.once('dataSourceAttached', function () {
_seed(Model, data, next);
});
}
}
function _seed(Model, data, next) {
if (!Array.isArray(data)) data = [data];
async.map(data, function (item, callback) {
debug('Seed %s: %s', Model.modelName, JSON.stringify(item).substr(0, 80));
Model.upsert(item, callback);
}, next);
}
}
require('util').inherits(Seed, require('events').EventEmitter);
Seed.prototype.plant = function (app, dir) {
var loopback = app.loopback;
eachModels(app, function (Model, name) {
global[name] = loopback.getModelByType(Model);
debug('inject model', name, '->', Model.modelName);
});
fs.readdirSync(dir).forEach(function (file) {
var seed = path.resolve(dir + '/' + file);
if (file.match(/\.(coffee|js)$/)) {
delete Module._cache[seed];
require(seed);
}
});
};
Seed.prototype.harvest = function (app, file, type) {
type = type || 'js';
var that = this;
var wait = 0;
var modelNames = Object.keys(app.models);
if (modelNames[0] && !app.models[modelNames[0]].dataSource) {
return app.models[modelNames[0]].once('dataSourceAttached', function () {
setTimeout(function () {
that.harvest(app, file, type);
}, 1000);
});
}
fs.mkdirpSync(file);
modelNames = modelNames.filter(function (name) {
// filter models that has data access funcions
return typeof app.models[name].all === 'function';
});
modelNames.forEach(function (modelName) {
wait += 1;
var Model = app.models[modelName];
var text = '';
Model.all(function (err, data) {
if (err) throw err;
data.forEach(function (d) {
text += codify(modelName, d, type);
});
if (data && data.length) {
fs.writeFileSync(file + '/' + modelName + '.' + type, text);
}
if (--wait === 0) {
that.emit('complete');
}
});
});
function codify(modelName, d, type) {
var str = modelName + '.seed({\n';
Object.keys(d.toObject()).forEach(function (f, index, array) {
if (d[f] === undefined) return;
str += ' ' + escape(f) + ': ' + quote(d[f]);
if (index !== array.length - 1) str += ',';
str += '\n';
});
str += '});';
return str + '\n';
}
function escape(f) {
return f.match(/[^_a-z]/i) ? "'" + f + "'" : f;
}
function quote(v) {
if (typeof v === 'string') {
if (v.match(/\n/)) {
return '"""\n ' +
v.replace(/#\{/g, '\\#{').replace(/\n/g, '\n ') +
'\n """';
} else {
return "'" + v.replace(/'/g, '\\\'') + "'";
}
}
if (v && typeof v === 'object' && v.constructor.name === 'Date') {
return "'" + v.toString().split(' GMT')[0] + "'";
} else if (v && typeof v === 'object') {
return JSON.stringify(v);
}
return v;
}
};