nested-builder
Version:
Tersely construct complex test fixture objects with the builder pattern.
59 lines • 2.07 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuilderBase = void 0;
const types_1 = require("./types");
class BuilderBase {
constructor(template) {
this.template = template;
this.underConstruction = {};
}
build() {
// Populate any missing fields.
for (const fieldName in this.template) {
if (!(fieldName in this.underConstruction)) {
const fieldTemplate = this.template[fieldName];
if (types_1.isDefault(fieldTemplate)) {
this.underConstruction[fieldName] = fieldTemplate.default;
}
else if (types_1.isGenerated(fieldTemplate)) {
this.underConstruction[fieldName] = fieldTemplate.generator();
}
else if (types_1.isPlural(fieldTemplate)) {
this.underConstruction[fieldName] = [];
}
else if (types_1.isNested(fieldTemplate)) {
const builder = new fieldTemplate.nested();
this.underConstruction[fieldName] = builder.build();
}
}
}
return this.underConstruction;
}
setScalar(fieldName, value) {
this.underConstruction[fieldName] = value;
return this;
}
addScalar(fieldName, value) {
this.ensureArray(fieldName);
this.underConstruction[fieldName].push(value);
return this;
}
setNested(fieldName, builder, block) {
block(builder);
this.underConstruction[fieldName] = builder.build();
return this;
}
addNested(fieldName, builder, block) {
this.ensureArray(fieldName);
block(builder);
this.underConstruction[fieldName].push(builder.build());
return this;
}
ensureArray(fieldName) {
if (!(fieldName in this.underConstruction)) {
this.underConstruction[fieldName] = [];
}
}
}
exports.BuilderBase = BuilderBase;
//# sourceMappingURL=builder.js.map