50 lines
2.4 KiB
JavaScript
50 lines
2.4 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.toPlain = exports.toPlains = exports.arrayItemToObject = void 0;
|
|
const isarray_1 = __importDefault(require("isarray"));
|
|
const utils_1 = require("./utils");
|
|
exports.arrayItemToObject = (arrayVal, Clazz, options) => {
|
|
return arrayVal.map((v) => isarray_1.default(v) ? exports.arrayItemToObject(v, Clazz, options) : classToObject(v, Clazz, options));
|
|
};
|
|
const classToObject = (instance, Clazz, options) => {
|
|
const obj = {};
|
|
const keyStore = utils_1.getKeyStore(Clazz);
|
|
keyStore.forEach((propertiesOption, key) => {
|
|
const isValueNotExist = options.distinguishNullAndUndefined ? utils_1.isUndefined : utils_1.isNullOrUndefined;
|
|
const instanceValue = isValueNotExist(instance[key]) ? propertiesOption.default : instance[key];
|
|
const { originalKey, afterSerializer, serializer, targetClass, optional } = propertiesOption;
|
|
const disallowIgnoreSerializer = propertiesOption.disallowIgnoreSerializer || !options.ignoreSerializer;
|
|
const disallowIgnoreAfterSerializer = propertiesOption.disallowIgnoreAfterSerializer || !options.ignoreAfterSerializer;
|
|
if (isValueNotExist(instanceValue)) {
|
|
if (!optional) {
|
|
throw new Error(`Property '${Clazz.name}.${key}' not found`);
|
|
}
|
|
return;
|
|
}
|
|
let value = serializer && disallowIgnoreSerializer ? serializer(instanceValue, instance, obj, options) : instanceValue;
|
|
if (value && targetClass) {
|
|
if (isarray_1.default(value)) {
|
|
value = exports.arrayItemToObject(value, targetClass, options);
|
|
}
|
|
else {
|
|
value = exports.toPlain(value, targetClass, options);
|
|
}
|
|
}
|
|
obj[originalKey] =
|
|
afterSerializer && disallowIgnoreAfterSerializer ? afterSerializer(value, instance, obj, options) : value;
|
|
});
|
|
return obj;
|
|
};
|
|
exports.toPlains = (instances, Clazz, options = {}) => {
|
|
if (!isarray_1.default(instances)) {
|
|
throw new Error(`${Clazz} instances must be an array`);
|
|
}
|
|
return instances.map((item) => classToObject(item, Clazz, options));
|
|
};
|
|
exports.toPlain = (instance, Clazz, options = {}) => {
|
|
return classToObject(instance, Clazz, options);
|
|
};
|