UNPKG

@mixtape/core

Version:

Supercharged fixture library for organizing and generating test data

71 lines 2.68 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("./utils"); /** * Class for generating object(s) from a template. * From a template the class can be used to generate one or more objects * with random data based on the types defined in the template. */ var ObjectBuilder = /** @class */ (function () { /** * Create a new `ObjectBuilder` * @param template - object template to generate object from * @param context - fixture context to use when generating data * @param generator - generator to use when generating numbers * @throws if template is not an object */ function ObjectBuilder(template, context, generator) { var _this = this; this._template = template; this._context = context; this._generator = generator; utils_1.ensure(function () { return utils_1.isObject(_this._template); }, "The template provided must be of type 'object'", TypeError); } /** * Create single object * @returns single `object` based on template * @throws on invalid template syntax */ ObjectBuilder.prototype.create = function () { return this.build(this._template, this._context); }; /** * Create array of objects * @param size - size of array to create * @returns `Array` of `objects` based on template * @throws on invalid template syntax */ ObjectBuilder.prototype.createMany = function (size) { var list = []; size = size ? size : this._generator.generate(); for (var i = 0; i < size; i++) { list.push(this.create()); } return list; }; ObjectBuilder.prototype.build = function (template, context) { var _this = this; return Object .keys(template) .reduce(function (o, k) { var value = template[k]; if (utils_1.isObject(value)) { o[k] = _this.build(value, context); return o; } if (utils_1.isArray(value)) { utils_1.ensure(function () { return value.length === 1 && typeof value[0] === 'string'; }, 'Array in template should (only) contain one type'); o[k] = context.createMany(value[0]); return o; } if (typeof value === 'string') { o[k] = context.create(value); return o; } throw new Error("Invalid template syntax '" + k + ": " + value + "'"); }, {}); }; return ObjectBuilder; }()); exports.default = ObjectBuilder; //# sourceMappingURL=object-builder.js.map