@martinmilo/verve
Version:
TypeScript domain modeling library with field-level authorization, business rule validation, and context-aware access control
70 lines • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldBuilder = void 0;
const constants_1 = require("../../constants");
const options_1 = require("../core/options");
class FieldBuilder {
constructor(Field, options = {}) {
this.Field = Field;
this.options = options;
}
getOption(option) {
return this.options[option];
}
setOption(option, value) {
this.options[option] = value;
}
toField(model) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const modelName = this[constants_1.FIELD_MODEL];
const fieldName = this[constants_1.FIELD_NAME];
return new this.Field({ name: fieldName, model: modelName }, {
...this.options,
nullable: (_a = this.options.nullable) !== null && _a !== void 0 ? _a : FieldBuilder.defaultOptions.nullable,
readable: (_b = this.options.readable) !== null && _b !== void 0 ? _b : FieldBuilder.defaultOptions.readable,
writable: (_c = this.options.writable) !== null && _c !== void 0 ? _c : FieldBuilder.defaultOptions.writable,
default: (_d = this.options.default) !== null && _d !== void 0 ? _d : FieldBuilder.defaultOptions.default,
compute: bindCompute(this.options.compute, model),
generator: (_h = (_e = this.options.generator) !== null && _e !== void 0 ? _e : (_g = (_f = this.Field).getGlobalGenerator) === null || _g === void 0 ? void 0 : _g.call(_f)) !== null && _h !== void 0 ? _h : FieldBuilder.defaultOptions.generator,
validators: bindValidators(this.options.validators, model),
});
}
}
exports.FieldBuilder = FieldBuilder;
FieldBuilder.defaultOptions = options_1.DEFAULT_FIELD_OPTIONS;
function bindValidators(providedValidators = [], model) {
const validators = providedValidators !== null && providedValidators !== void 0 ? providedValidators : FieldBuilder.defaultOptions.validators;
if (!validators) {
return [];
}
// Bind the model to the validator and preserve the original function properties (i.e. __isLazy identifier)
return validators.map(validator => {
if (typeof validator === 'function') {
const boundValidator = (value) => validator(value, model);
Object.assign(boundValidator, validator);
Object.defineProperty(boundValidator, 'name', {
value: validator.name,
configurable: true
});
return boundValidator;
}
return validator;
});
}
function bindCompute(providedCompute, model) {
const compute = providedCompute !== null && providedCompute !== void 0 ? providedCompute : FieldBuilder.defaultOptions.compute;
if (!model) {
return compute;
}
if (typeof compute === 'function') {
const boundCompute = () => compute(model);
Object.assign(boundCompute, compute);
Object.defineProperty(boundCompute, 'name', {
value: compute.name,
configurable: true
});
return boundCompute;
}
return compute;
}
//# sourceMappingURL=FieldBuilder.js.map