mocker-data-generator
Version:
A simplified way to generate mock data, builds using a simple schema and with the FakerJs
208 lines (207 loc) • 7.86 kB
JavaScript
import { __assign, __extends, __spreadArray } from "tslib";
import { Generator } from './Generator';
import { evalWithContextData, fieldArrayCalcLength, iamLastParent, isArray, isConditional, isObject } from './utils';
var iterate = function (obj, res, currentPath) {
var _this = this;
if (!currentPath) {
currentPath = [];
}
Object.keys(obj).map(function (k) {
var value = obj[k];
var path = currentPath.slice(0);
path.push(k);
if (iamLastParent(value)) {
if (path) {
if (isArray(value)) {
if (value[0] && value[0].virtual) {
_this.virtualPaths.push(path.toString());
}
}
else {
if (value.virtual) {
_this.virtualPaths.push(path.toString());
}
}
}
var key = '';
if (!isConditional(k)) {
key = k;
}
else {
var keykey = k.split(',');
if (evalWithContextData(keykey[0], _this.object, _this.DB, _this.generators)) {
key = keykey[1];
}
}
if (key !== '') {
res[key] = _this.proccessLeaf(value, key);
}
}
else {
res[k] = {};
iterate.call(_this, value, res[k], path);
}
});
};
var Schema = /** @class */ (function (_super) {
__extends(Schema, _super);
function Schema(name, cfg, options, generators) {
if (generators === void 0) { generators = {}; }
var _this = _super.call(this) || this;
_this.schema = cfg;
_this.name = name;
_this.options = options;
_this.generators = generators;
// Temp fields
_this.DB = {};
_this.object = {};
_this.virtualPaths = [];
return _this;
}
Schema.prototype.proccessLeaf = function (field, fieldName) {
var _this = this;
if (isArray(field)) {
var fieldConfig_1 = field[0];
if (field.length > 1) {
fieldConfig_1 = { values: field };
}
var na = Array();
if (fieldConfig_1.concat) {
na = evalWithContextData(fieldConfig_1.concat, this.object, this.DB, this.generators);
// Strict Mode
na = fieldConfig_1.concatStrict
? __spreadArray([], Array.from(new Set(na)), true) : na;
}
var length_1 = fieldArrayCalcLength(field.length > 1 ? fieldConfig_1.values : fieldConfig_1, na.length, this);
var array = Array.from(new Array(length_1)).reduce(function (acc, el, index) {
var self = acc.slice(0);
acc.push(_this.generateField(fieldName, fieldConfig_1, index, length_1, self));
return acc;
}, []);
return array.concat(na);
}
else {
return this.generateField(fieldName, field);
}
};
Schema.prototype.generateField = function (fieldName, cfg) {
var _a, _b;
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = {};
var customGenerators = Object.keys(this.generators);
var ownedByMocker = [
'self',
'db',
'hasOne',
'hasMany',
'static',
'function',
'values',
'incrementalId'
];
var generators = __spreadArray(__spreadArray([], ownedByMocker, true), customGenerators, true);
var keys = Object.keys(cfg);
var key = keys.reduce(function (acc, val) {
if (generators.includes(val)) {
acc = val;
}
return acc;
}, 'noKey');
if (key === 'noKey' && !keys.includes('eval')) {
throw "Error: Invalid or missing generator".concat(fieldName !== 'root' ? " on field ".concat(fieldName) : '', ". Please use one of this generators [").concat(generators.join(','), "], note that if your generator doesnt appear in the list maybe you forgot to add it.");
}
if (keys.includes('eval') && keys.length === 1) {
key = 'eval';
}
try {
result = customGenerators.includes(key)
? this.custom({
generator: (_a = this.generators[key]) === null || _a === void 0 ? void 0 : _a.library,
run: (_b = this.generators[key]) === null || _b === void 0 ? void 0 : _b.run,
input: cfg[key],
eval: cfg.eval
})
: this[key].apply(this, __spreadArray([__assign(__assign({}, cfg), { generators: this.generators })], args, false));
}
catch (e) {
throw 'Error: "' + key + '" ' + e;
}
return result;
};
Schema.prototype.buildSingle = function (schema) {
if (iamLastParent(schema)) {
this.object = this.proccessLeaf(schema, 'root');
}
else {
iterate.call(this, schema, this.object);
}
};
Schema.prototype.build = function (generators, db) {
var _this = this;
if (generators === void 0) { generators = {}; }
if (db === void 0) { db = {}; }
this.generators = generators;
this.object = {};
this.DB = db ? db : {};
this.DB[this.name] = this.DB[this.name] ? this.DB[this.name] : [];
if (Number.isInteger(this.options)) {
Array.from(new Array(this.options)).map(function () {
_this.buildSingle(_this.schema);
_this.DB[_this.name].push(_this.object);
_this.object = {};
});
}
else if (isObject(this.options) && this.options.max) {
var max = this.options.max;
var min = this.options.min ? this.options.min : 0;
var length = Math.floor(Math.random() * (max - min + 1) + min);
Array.from(new Array(length)).map(function () {
_this.buildSingle(_this.schema);
_this.DB[_this.name].push(_this.object);
_this.object = {};
});
}
else if (isObject(this.options) && this.options.uniqueField) {
var f_1 = this.options.uniqueField;
var entityConfig_1 = this.schema;
var possibleValues = void 0;
if (f_1 === '.') {
possibleValues = this.schema.values;
}
else {
if (this.schema[f_1]) {
if (isArray(this.schema[f_1].values)) {
possibleValues = this.schema[f_1].values;
}
else {
possibleValues = this.schema[f_1];
}
}
else {
throw "The field \"".concat(f_1, "\" not exists.");
}
}
if (!isArray(possibleValues)) {
throw "The posible values value is not an Array";
}
possibleValues.map(function (value) {
if (f_1 === '.') {
return;
}
entityConfig_1[f_1] = { static: value };
_this.buildSingle(entityConfig_1);
_this.DB[_this.name].push(_this.object);
_this.object = {};
});
}
else {
throw "An string \"".concat(this.options, "\" is not recognized as a parameter.");
}
return this.DB[this.name];
};
return Schema;
}(Generator));
export { Schema };