@toreda/strong-types
Version:
Better TypeScript code in fewer lines.
109 lines (108 loc) • 3.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapParser = void 0;
const map_1 = require("../map");
const state_1 = require("./parser/state");
/**
* Recursively parse provided object properties.
*
* @category Strong Map
*/
class MapParser {
parse(map, data, options) {
if (!map) {
return false;
}
if (!data) {
return false;
}
const parseState = new state_1.MapParserState(options);
return this.parseMap(map, data, parseState);
}
parseStrongKey(key, value, _parseState) {
if (!key || value === undefined) {
return;
}
if (key.baseType !== 'StrongType') {
return;
}
const strongValue = value;
// When value is also a StrongType invoke it to get its value. Otherwise set
// the strong key with value.
if (strongValue != null && strongValue.baseType === 'StrongType') {
key(strongValue());
}
else {
key(value);
}
}
parseKey(map, keyName, value, _parseState) {
if (!map) {
return false;
}
if (value === undefined) {
return false;
}
if (typeof keyName !== 'string' || !keyName) {
return false;
}
if (value === null) {
map[keyName] = null;
return true;
}
let result;
const strongValue = value;
if (strongValue.hasOwnProperty('typeId') && strongValue.baseType === 'StrongType') {
result = strongValue();
}
else {
result = value;
}
if (typeof map[keyName] !== typeof result) {
return false;
}
map[keyName] = result;
return true;
}
/**
* Recursively parse map and children.
* @param map Map to match properties against and store parsed values.
* @param json Object to parse into map.
* @param parseState Internal state for current parse.
* @returns Boolean indicating success or failure.
* true - Map parse successful.
* false - Map parse not successful.
*/
parseMap(map, data, parseState) {
var _a;
if (!map) {
return false;
}
if (typeof data === 'undefined' || data === {}) {
return false;
}
const keys = Object.keys(map);
for (const keyName of keys) {
const child = map[keyName];
const keyValue = data[keyName];
// Skip built-in properties.
if (!map.hasOwnProperty(keyName)) {
continue;
}
// Child is also a StrongMap. Parse it recursively.
if (child instanceof map_1.StrongMap) {
this.parseMap(child, keyValue, parseState);
}
else if (((_a = child) === null || _a === void 0 ? void 0 : _a.baseType) === 'StrongType') {
// Child is a StrongType.
this.parseStrongKey(child, keyValue, parseState);
}
else if (typeof child !== 'object') {
// Child is not a StrongType and not an object.
this.parseKey(map, keyName, keyValue, parseState);
}
}
return true;
}
}
exports.MapParser = MapParser;