dr-seeder
Version:
Seed data with ease
125 lines (102 loc) • 3.25 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Seed = function () {
function Seed(name, collection, options) {
(0, _classCallCheck3.default)(this, Seed);
if (!collection || !options) {
var msg = 'Please supply a collection to seed and options for seeding.';
throw new Error(msg);
} else {
this.name = name;
this.collection = collection;
this.options = options;
this.isDataArray = this.options.data instanceof Array;
this.context = {
name: name,
collection: collection,
startResponse: null
};
this.seed();
}
}
(0, _createClass3.default)(Seed, [{
key: 'shouldSeed',
value: function shouldSeed() {
var condition = this.options.condition;
return condition ? condition.call(this.context) : true;
}
}, {
key: 'seed',
value: function seed() {
var options = this.options;
var data = options.data;
var onStart = options.onStart;
var onFinish = options.onFinish;
var onSkip = options.onSkip;
if (this.shouldSeed()) {
if (onStart) {
this.context.startResponse = onStart.call(this.context);
}
this.plant(data);
if (onFinish) {
onFinish.call(this.context);
}
} else if (onSkip) {
onSkip.call(this.context);
}
}
}, {
key: 'plant',
value: function plant(data) {
var loopLength = this._loopLength();
for (var i = 0; i < loopLength; i++) {
var value = this.isDataArray ? data[i] : data.call(this.context, i);
this.collection.insert(value);
}
}
}, {
key: '_loopLength',
value: function _loopLength() {
var random = function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
return this.isDataArray ? this.options.data.length : random(this.options.min, this.options.max);
}
}]);
return Seed;
}();
var Seeder = {
settings: {
condition: function condition() {
return this.collection.find().count() === 0;
},
min: 1,
max: 20,
onStart: function onStart() {
console.log('Seeder: ' + this.name + '\t => Started');
},
onFinish: function onFinish() {
console.log('Seeder: ' + this.name + '\t => Finished');
},
onSkip: function onSkip() {
console.log('Seeder: ' + this.name + '\t => Skipped');
}
},
config: function config(options) {
(0, _assign2.default)(this.settings, options);
},
seed: function seed(name, collection, options) {
var finalOptions = (0, _assign2.default)({}, this.settings, options);
return new Seed(name, collection, finalOptions);
}
};
exports.default = Seeder;