UNPKG

transformable

Version:

Transforms plain objects to class instances and vice versa (a lightweight alternative to 'class-transformer')

44 lines 1.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.instanceToPlain = exports.plainToInstance = void 0; const storage_1 = require("./storage"); function plainToInstance(sourcePlain, targetClass, sourceContext) { const targetInstance = new targetClass(); const targetPrototype = targetClass.prototype; for (let [attributeName, attributeValue] of Object.entries(sourcePlain)) { if (attributeValue === undefined) { continue; } if (attributeValue !== null) { const transformer = (0, storage_1.getTransformation)(targetPrototype, attributeName)?.input; if (transformer) { attributeValue = transformer(attributeValue, { source: sourceContext }); } } targetInstance[attributeName] = attributeValue; } return targetInstance; } exports.plainToInstance = plainToInstance; function instanceToPlain(sourceInstance, targetContext) { const targetPlain = {}; const sourcePrototype = Object.getPrototypeOf(sourceInstance); for (let [attributeName, attributeValue] of Object.entries(sourceInstance)) { if (attributeValue === undefined) { continue; } if (attributeValue !== null) { const transformer = (0, storage_1.getTransformation)(sourcePrototype, attributeName)?.output; if (transformer) { attributeValue = transformer(attributeValue, { target: targetContext }); } if (attributeValue === undefined) { continue; } } targetPlain[attributeName] = attributeValue; } return targetPlain; } exports.instanceToPlain = instanceToPlain; //# sourceMappingURL=functions.js.map