UNPKG

objectypes

Version:

A type-safe library to transform and validate objects

42 lines (41 loc) 1.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mapObject = void 0; const mapping_1 = require("./metadata/mapping"); const property_1 = require("./metadata/property"); function processValue(property, obj) { const { mapPropertyKey, mapTransformer } = property; if (mapPropertyKey) { return obj[mapPropertyKey]; } if (!mapTransformer) { throw new Error('Invalid mapping. No property or transformation found.'); } return mapTransformer.transform(obj); } function mapObject(targetKlass, objKlass, obj) { var _a, _b; const targetObj = new targetKlass(); const mappedProperties = (_a = (0, mapping_1.findClassMappingMetadata)(targetKlass)) === null || _a === void 0 ? void 0 : _a.filter(property => property.mapTarget.name === objKlass.name); // eslint-disable-next-line no-unused-expressions mappedProperties === null || mappedProperties === void 0 ? void 0 : mappedProperties.forEach(property => { const value = processValue(property, obj); Reflect.set(targetObj, property.propertyKey, value); }); // Get regular properties ignoring mappedProperties const mappedKeys = mappedProperties === null || mappedProperties === void 0 ? void 0 : mappedProperties.map(mapped => mapped.propertyKey); const properties = (_b = (0, property_1.findClassPropertiesMetadata)(targetKlass)) === null || _b === void 0 ? void 0 : _b.filter(property => { if (mappedKeys) { // Avoid duplicated properties return !mappedKeys.includes(property.propertyKey); } return true; }); // eslint-disable-next-line no-unused-expressions properties === null || properties === void 0 ? void 0 : properties.forEach(property => { const { propertyKey } = property; Reflect.set(targetObj, propertyKey, obj[propertyKey]); }); return targetObj; } exports.mapObject = mapObject;