Skip to content

Instantly share code, notes, and snippets.

@fernandolguevara
Last active September 25, 2019 18:43
Show Gist options
  • Save fernandolguevara/75a2a3edc7e4f3244766 to your computer and use it in GitHub Desktop.
Save fernandolguevara/75a2a3edc7e4f3244766 to your computer and use it in GitHub Desktop.
Sails.js seed method
var nodepath = require('path'),
seedInfo;
function hasSeedInfo() {
var seedPath = nodepath.resolve(sails.config.paths.config, 'env', sails.config.environment, 'seed');
try {
seedInfo = require(seedPath)
} catch (e) {}
return !_.isUndefined(seedInfo) && !_.isNull(seedInfo);
}
function doSeed(callback) {
var self = this;
_.each(seedInfo, function(value, key) {
var model = self[key];
if (!_.isNull(model) && !_.isUndefined(model)) {
model.count().exec(function(err, count) {
if (!err && count === 0 && !_.isEmpty(value)) {
sails.log.debug('Seeding ' + key + '...');
model.createEach(value).exec(function(err, results) {
if (err) {
sails.log.debug(err);
} else {
sails.log.debug((key + ' seed planted').grey);
}
});
} else {
sails.log.debug((key + ' had models, so no seed needed').grey);
}
});
}
});
callback();
}
module.exports.bootstrap = function(cb) {
// It's very important to trigger this callback method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
if (sails.config.seed && hasSeedInfo()) {
async.series([doSeed], cb);
}
};
//app/config/env/development/seed.js
module.exports = {
Country: [{
name: 'Argentina'
}, {
name: 'EEUU'
}, {
name: 'Country 3'
}],
OtherModel: [{
prop1: 'value 1',
prop2: 1
}, {
prop1: 'value 2',
prop2: 5
}]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment