This repository has been archived by the owner on Aug 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
112 lines (100 loc) · 2.74 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
'use strict';
//dependencies
var async = require('async'),
path = require('path'),
libPath = path.join(__dirname, 'lib');
// model extras
var seed = require(path.join(libPath, 'seed')),
seedArray = require(path.join(libPath, 'seedArray')),
seedObject = require(path.join(libPath, 'seedObject'));
module.exports = function(sails){
return {
initialize: function(done){
//later on wait for this/these event(s)
//to apply methods to models
var eventsToWaitFor = [];
//wait for orm
//and pub sub hooks
//to be loaded
//for methods to
//be attached to models
if(sails.hooks.orm) eventsToWaitFor.push('hook:orm:loaded');
if(sails.hooks.pubsub) eventsToWaitFor.push('hook:pubsub:loaded');
sails
.after(eventsToWaitFor, function(){
//bind additional methods
//to models
//then seed models
//and let sails continue
patchAttributes(function(){
patch(function(){
seeds(done);
});
});
});
}
};
};
function getModelsByPriority(){
return _.sortBy(_.keys(sails.models), function(key){
return sails.models[key].priority;
});
};
function seeds(callback){
if(sails.config.seeds.disable){
callback()
} else {
async.eachSeries(getModelsByPriority(), function(model, cb){
if(sails.models[model].seed && sails.config.seeds[model] && !(sails.config.seeds[model].active === false)){
sails.models[model].seed(cb);
} else {
cb();
}
}, function(err){
if(err) sails.log.error('Your seeds were not planted correctly');
else sails.log.info('Your seeds are ready to grow!');
callback();
});
}
};
function patch(cb){
async.each(_.toArray(sails.models), function(model, callback){
if(model.globalId){
seed(model);
seedArray(model);
seedObject(model);
callback();
} else {
callback();
}
}, function(){
cb();
});
}
function patchAttributes(callback){
async.each(_.toArray(sails.models), function(model, cb){
var data = sails.config.seeds[model.identity];
if(data){
var extend = {};
if(_.some([data.overwrite, data.unique, data.priority], _.isDefined)){
extend.seedData = data.data ? data.data : [];
extend.overwrite = data.overwrite;
extend.unique = data.unique;
extend.priority = data.priority;
} else {
extend.seedData = data;
extend.overwrite = false;
extend.priority = 0;
}
_.extend(model, extend);
cb();
} else {
_.extend(model, {
seedData: null
});
cb();
}
}, function(){
callback();
});
}