mapper-tsk
Version:
mapper tool to use with or without NodeTskeleton template project
110 lines (109 loc) • 4.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class Mapper {
mapObject(source, destination, profile) {
if (!source) {
return destination;
}
try {
const keysToMap = !profile
? Object.keys(destination)
: Object.keys(profile);
if (!profile) {
keysToMap.forEach((destinationKey) => {
if (typeof destination[destinationKey] === "boolean") {
destination[destinationKey] = source[destinationKey];
}
else {
destination[destinationKey] = source[destinationKey] || null;
}
});
}
else {
keysToMap.forEach((keyToMap) => {
const mappingProfile = profile[keyToMap];
if (typeof mappingProfile === "string") {
this.createDeepChainingDestinationObject(profile[keyToMap], destination, this.getChainingDeepSourceObjectValue(keyToMap, source), null);
}
else {
this.createDeepChainingDestinationObject(mappingProfile.destinationKey, destination, null, () => mappingProfile.mappingFunction(this.getChainingDeepSourceObjectValue(keyToMap, source)));
}
});
}
}
catch (error) {
console.log("mapper-tsk error: ", error);
}
return destination;
}
mapArray(source, activator, profile) {
const destination = [];
if ((source === null || source === void 0 ? void 0 : source.length) === 0) {
return destination;
}
source.forEach((sElement) => {
const dElement = activator();
destination.push(this.mapObject(sElement, dElement, profile));
});
return destination;
}
activator(type) {
return new type();
}
getChainingDeepSourceObjectValue(sourceChainingKeys, chainingSource) {
const keys = sourceChainingKeys.split(".");
if ((sourceChainingKeys === null || sourceChainingKeys === void 0 ? void 0 : sourceChainingKeys.length) === 0) {
return null;
}
let value = null;
keys.forEach((key) => {
if (!value) {
value = chainingSource[key];
return;
}
value = value[key];
});
return value;
}
createDeepChainingDestinationObject(destinationChainingKeys, destination, value, functionValue) {
function deepNavigation(limit, index, destinationKeys, destination) {
const key = destinationKeys[index];
if (!destination[key]) {
if (index < limit) {
destination[key] = {};
deepNavigation(limit, index + 1, destinationKeys, destination[key]);
}
else {
if (!functionValue) {
if (value && typeof value === "object") {
destination[key] = Object.assign({}, value);
}
else if (typeof value === "boolean") {
destination[key] = value;
}
else {
destination[key] = value || null;
}
}
else {
destination[key] = functionValue();
}
}
}
else {
if (index < limit) {
deepNavigation(limit, index + 1, destinationKeys, destination[key]);
}
}
}
const destinationKeys = destinationChainingKeys.split(".");
if ((destinationKeys === null || destinationKeys === void 0 ? void 0 : destinationKeys.length) === 0) {
return;
}
const limit = destinationKeys.length - 1;
const index = 0;
deepNavigation(limit, index, destinationKeys, destination);
}
}
const mapper = new Mapper();
exports.default = mapper;