forked from bredikhin/barrels
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
259 lines (214 loc) · 9.8 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
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
'use strict';
/**
* Fixted: A simple way to populate a test database for Sails.js v1.
*
* @module Fixted
*/
/**
* A function to call once work is finished.
*
* @callback doneCb
* @returns void
*/
/**
* Dependencies
*/
const fs = require('fs');
const path = require('path');
const async = require('async');
const {cloneDeep, forEach, omit, pick} = require('lodash');
class Fixted {
// Fixture objects loaded from the JSON files
data = {};
// Map fixture positions in JSON files to the real DB IDs
idMap = {};
// The list of associations by model
associations = {};
// The list of the fixtures model names
modelNames = [];
/**
* Load data fixtures into memory.
*
* @param {string} [sourceFolder=/test/fixtures]
* @returns this
*/
constructor(sourceFolder) {
// Load the fixtures
sourceFolder = sourceFolder || process.cwd() + '/test/fixtures';
const files = fs.readdirSync(sourceFolder);
for (let i = 0; i < files.length; i++) {
if (['.json', '.js'].indexOf(path.extname(files[i]).toLowerCase()) !== -1) {
const modelName = path.basename(files[i]).split('.')[0].toLowerCase();
this.data[modelName] = require(path.join(sourceFolder, files[i]));
}
}
this.modelNames = Object.keys(this.data);
return this;
}
/**
* Build associations for the loaded data fixtures.
*
* @param {string[]|doneCb} collections - Array of model names, or a callback function.
* @param {doneCb} [done] - A callback function.
* @returns void
*/
associate(collections, done) {
if (!Array.isArray(collections)) {
done = collections;
collections = this.modelNames;
}
// Add associations whenever needed
async.each(collections, (modelName, nextModel) => {
const thisModel = sails.models[modelName];
if (thisModel) {
const fixtureObjects = cloneDeep(this.data[modelName]);
async.each(fixtureObjects, (item, nextItem) => {
// Item position in the file
const itemIndex = fixtureObjects.indexOf(item);
// Find and associate
thisModel.findOne(this.idMap[modelName][itemIndex]).exec((err, model) => {
if (err) {
return nextItem(err);
}
if (!model) {
return nextItem(new Error('Could not find the model'));
}
let shouldUpdate = false;
// Pick associations only
item = pick(item, Object.keys(this.associations[modelName]));
forEach(item, (val, attr) => {
const association = this.associations[modelName][attr];
const joined = association[association.type];
// Required associations should have been added by .populate()
if (association.required) {
return;
}
shouldUpdate = true;
if (!Array.isArray(item[attr])) {
model[attr] = this.idMap[joined][item[attr] - 1];
} else {
model[attr] = [];
for (let j = 0; j < item[attr].length; ++j) {
model[attr].push(this.idMap[joined][item[attr][j] - 1]);
}
}
});
if (shouldUpdate) {
model = JSON.parse(JSON.stringify(model)); // force model to a plain object, or Waterline will not be happy
thisModel.updateOne(this.idMap[modelName][itemIndex]).set(model).exec((err) => {
if (err) {
return nextItem(err);
}
return nextItem();
});
} else {
return nextItem();
}
});
}, nextModel);
} else {
nextModel();
}
}, done);
}
/**
* Populate the database with the loaded data fixtures.
*
* @param {string[]|doneCb} collections - An array of model names to populate, in order.
* @param {boolean|doneCb} [done] - A callback function.
* @param {boolean} [autoAssociations] - Set to `false` to disable auto associations.
* @returns void
*/
populate(collections, done, autoAssociations) {
let preserveLoadOrder = true;
if (!Array.isArray(collections)) {
autoAssociations = done;
done = collections;
collections = this.modelNames;
preserveLoadOrder = false;
} else {
forEach(collections, (collection, key) => {
collections[key] = collection.toLowerCase();
});
}
autoAssociations = !(autoAssociations === false); // auto associations are turned on, unless explicitly turned off
// Populate each table / collection
async[preserveLoadOrder ? 'eachSeries' : 'each'](collections, (modelName, nextModel) => {
let thisModel = sails.models[modelName];
if (thisModel) {
// Cleanup existing data in the table / collection
thisModel.destroy({}).exec((err) => {
if (err) {
return nextModel(err);
}
// Save model's association information
this.associations[modelName] = {};
for (let i = 0; i < thisModel.associations.length; ++i) {
const alias = thisModel.associations[i].alias;
this.associations[modelName][alias] = thisModel.associations[i];
this.associations[modelName][alias].required = thisModel.attributes[alias].required;
}
// Insert all the fixture items
this.idMap[modelName] = [];
const fixtureObjects = cloneDeep(this.data[modelName]);
async.eachSeries(fixtureObjects, (item, nextItem) => {
// Item position in the file
const itemIndex = fixtureObjects.indexOf(item);
for (const alias in this.associations[modelName]) {
if (Object.prototype.hasOwnProperty.call(this.associations[modelName], alias)) {
if (this.associations[modelName][alias].required) {
// With required associations present, the associated fixtures
// must be already loaded, so we can map the ids
const collectionName = this.associations[modelName][alias].collection; // many-to-many
const associatedModelName = this.associations[modelName][alias].model; // one-to-many
if (Array.isArray(item[alias]) && collectionName) {
if (!this.idMap[collectionName]) {
return nextItem(
new Error('Please provide a loading order acceptable for required associations')
);
}
for (let i = 0; i < item[alias].length; i++) {
item[alias][i] = this.idMap[collectionName][item[alias][i] - 1];
}
} else if (associatedModelName) {
if (!this.idMap[associatedModelName]) {
return nextItem(
new Error('Please provide a loading order acceptable for required associations')
);
}
item[alias] = this.idMap[associatedModelName][item[alias] - 1];
}
} else if (autoAssociations) {
// The order is not important, so we can strip
// associations data and associate later
item = omit(item, alias);
}
}
}
// Insert
thisModel.create(item).meta({fetch: true}).exec((err, model) => {
if (err) {
return nextItem(err);
}
// Primary key mapping
this.idMap[modelName][itemIndex] = model[thisModel.primaryKey];
nextItem();
});
}, nextModel);
});
} else {
nextModel();
}
}, (err) => {
if (err) {
return done(err);
}
// Create associations if requested
if (autoAssociations) {
return this.associate(collections, done);
}
done();
});
}
}
module.exports = Fixted;