bc-node-sdk
Version:
BetterCommerce's NodeJS SDK encapsulates the base framework for all the Next.js applications.
46 lines (45 loc) • 1.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class Mapper {
/**
* Creates a new instance of the mapper with the given mapping rules.
*
* @param {MappingRule<T, U>} mappingRules The mapping rules to be used by the mapper.
*/
constructor(mappingRules) {
this.mappingRules = mappingRules;
}
/**
* Maps an entity of type T to an object of type U using the mapping rules specified during the
* creation of the mapper. The mapping rules are used to extract values from the entity and
* assign them to the corresponding properties of the mapped object. If a mapping rule returns
* an object, the method will recursively call itself to map the object. If a mapping rule
* returns an array of objects, the method will map each object in the array. If a mapping rule
* returns a primitive value, the method will assign the value to the corresponding property of
* the mapped object.
*
* @param {T} entity The entity to be mapped.
* @returns {U} The mapped object.
*/
map(entity) {
const mappedObject = {};
for (const key in this.mappingRules) {
const value = this.mappingRules[key](entity);
// Handle nested object mapping
if (value instanceof Object && !(value instanceof Array)) {
mappedObject[key] = value.map
? value.map((item) => item)
: value;
}
// Handle array of nested objects
else if (Array.isArray(value)) {
mappedObject[key] = value.map((item) => item instanceof Object && item.map ? item.map(item) : item);
}
else {
mappedObject[key] = value;
}
}
return mappedObject;
}
}
exports.default = Mapper;