@ilhamtahir/ts-mapper
Version:
[](https://www.npmjs.com/package/@ilhamtahir/ts-mapper) [](https://www.npmjs.com/package/@ilhamtahir/ts-mapper)
46 lines • 1.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.transform = transform;
const metadata_storage_1 = require("../metadata/metadata.storage");
// 支持嵌套路径读取
function getValue(obj, path) {
return path.split('.').reduce((acc, key) => acc?.[key], obj);
}
// 支持嵌套路径赋值
function setValue(obj, path, value) {
const keys = path.split('.');
const lastKey = keys.pop();
const target = keys.reduce((acc, key) => (acc[key] ??= {}), obj);
target[lastKey] = value;
}
function transform(mapper, method, input, outputType) {
const output = new outputType();
const mappings = metadata_storage_1.metadataStorage.getMappings(mapper.constructor, method);
const usedTargetKeys = new Set();
// 1️⃣ 显式字段映射
for (const mapping of mappings) {
const value = getValue(input, mapping.source);
setValue(output, mapping.target, value);
usedTargetKeys.add(mapping.target);
}
// 2️⃣ 自动字段匹配(字段名一致 + typeof 一致)
const inputKeys = Object.keys(input || {});
const outputKeys = new Set([
...Object.getOwnPropertyNames(output),
...Object.getOwnPropertyNames(Object.getPrototypeOf(output)),
]);
for (const key of inputKeys) {
if (outputKeys.has(key) && !usedTargetKeys.has(key)) {
const inputValue = input[key];
const outputValue = output[key];
const inputType = typeof inputValue;
const outputTypeGuess = typeof outputValue;
// 若输出初始值是 undefined,则只检查 input 是否为 object、number、string 等合理值
if (outputValue === undefined || inputType === outputTypeGuess) {
output[key] = inputValue;
}
}
}
return output;
}
//# sourceMappingURL=transformer.js.map