UNPKG

transformable

Version:

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

39 lines 1.54 kB
import { getTransformation } from './storage'; export 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 = getTransformation(targetPrototype, attributeName)?.input; if (transformer) { attributeValue = transformer(attributeValue, { source: sourceContext }); } } targetInstance[attributeName] = attributeValue; } return targetInstance; } export 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 = getTransformation(sourcePrototype, attributeName)?.output; if (transformer) { attributeValue = transformer(attributeValue, { target: targetContext }); } if (attributeValue === undefined) { continue; } } targetPlain[attributeName] = attributeValue; } return targetPlain; } //# sourceMappingURL=functions.js.map