UNPKG

objectypes

Version:

A type-safe library to transform and validate objects

47 lines (46 loc) 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildObject = void 0; const property_1 = require("../metadata/property"); const apply_reductions_1 = require("./apply-reductions"); const apply_transformations_to_object_1 = require("./apply-transformations-to-object"); const extract_value_from_json_1 = require("./extract-value-from-json"); const process_value_type_1 = require("./process-value-type"); const validate_value_definition_1 = require("./validate-value-definition"); function buildObject(targetClass, jsonObject) { const targetObject = new targetClass(); const propertyMetadatas = (0, property_1.findClassPropertiesMetadata)(targetClass); if (!propertyMetadatas) { return targetObject; } for (const propertyMetadata of propertyMetadatas) { const { propertyKey, nullable, defaultValue } = propertyMetadata; const wereReductionsApplied = (0, apply_reductions_1.applyReductionsToObject)(targetClass, targetObject, jsonObject, propertyMetadata); if (wereReductionsApplied) { continue; } const value = (0, extract_value_from_json_1.extractValueFromJsonObject)(propertyMetadata, jsonObject); if (nullable && value === undefined) { if (defaultValue !== undefined) { Reflect.set(targetObject, propertyKey, defaultValue); } continue; } (0, validate_value_definition_1.validateValueDefinition)(propertyMetadata, targetClass, value); const typedValue = (0, process_value_type_1.processValueType)(propertyMetadata, value); const transformedValue = (0, apply_transformations_to_object_1.applyTransformationsToObject)(targetClass, propertyMetadata, typedValue); const finalValue = processNestedValue(propertyMetadata, transformedValue); Reflect.set(targetObject, propertyKey, finalValue); } return targetObject; } exports.buildObject = buildObject; function processNestedValue(propertyMetadata, transformedValue) { const { type } = propertyMetadata; if (type === undefined || type === Date) { return transformedValue; } return Array.isArray(transformedValue) ? transformedValue.map(val => buildObject(type, val)) : buildObject(type, transformedValue); }