@martinmilo/verve
Version:
TypeScript domain modeling library with field-level authorization, business rule validation, and context-aware access control
58 lines • 2.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueInitializer = void 0;
const field_1 = require("../../field");
const constants_1 = require("../../constants");
class ValueInitializer {
static initialize(model, data = {}, params = { isHydrating: false }) {
const fields = model[constants_1.MODEL_FIELDS]();
for (const [fieldKey, field] of Object.entries(fields)) {
const fieldName = fieldKey.replace('$', '');
// Skip if field is computed
if (field.options.compute) {
continue;
}
const initialValue = this.getInitialValue(data[fieldName], {
...field.options,
isHydrating: params.isHydrating
});
// Skip if value is undefined, we don't set uninitialized values on the model instance
if (initialValue === undefined) {
continue;
}
// Set value on the model state
const state = model[constants_1.MODEL_STATE]();
state[fieldName] = initialValue;
// Temporarily set values on model with readable/writable as true until they get validated
Object.defineProperty(model, fieldName, {
value: initialValue,
writable: true,
enumerable: true,
configurable: true,
});
}
}
static getInitialValue(value, options) {
if (value !== undefined) {
return value;
}
// If we are hydrating, we don't want to set any values
// Example: We're instantiating a model with "from" method, we don't want to generate any values
if (options.isHydrating) {
return undefined;
}
// Creating new instance with either default or generated (if eager) value
// Prefer default value over generated value
if (options.default) {
return options.default;
}
// If we have an eager generator, we want to generate a value
const eagerGenerator = field_1.Field.getEagerGenerator(options);
if (eagerGenerator) {
return eagerGenerator();
}
return undefined;
}
}
exports.ValueInitializer = ValueInitializer;
//# sourceMappingURL=ValueInitializer.js.map