All files / src/utils mapping-util.ts

62.58% Statements 102/163
41.94% Branches 39/93
75% Functions 9/12
57.78% Lines 78/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354                              7x         7x       7x               7x           7x 7x   43x 43x 43x   138x 138x                   7x         168x 168x   336x 322x 322x   322x       40x   282x 12x   12x 12x   270x 22x   22x 22x     248x                     248x       248x                             248x     282x 2x   280x   280x                                                                                                                           280x 280x 280x 121x   159x                             7x 8x 8x 30x 30x       8x 22x 22x         8x 2x 2x         2x     2x         7x         2x 2x             2x 2x               2x     7x 8x     28x 28x     28x 14x   14x 14x                                                 7x                             7x                   7x                 7x       74x 74x             7x 405x     7x 404x   7x  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import {
  CONSTANT_FIELD_JSON_TYPE,
  IPropertyField,
  PROPERTY_FIELD_JSON_TYPE,
} from '../contracts/mapping';
import {
  DocumentDefinition,
  PaddingField,
} from '../models/document-definition.model';
import {
  ErrorInfo,
  ErrorLevel,
  ErrorScope,
  ErrorType,
} from '../models/error.model';
import { MappedField, MappingModel } from '../models/mapping.model';
import { ConfigModel } from '../models/config.model';
import { Field } from '../models/field.model';
import { IField } from '../contracts/common';
 
/**
 * Static routines for handling mappings.
 */
export class MappingUtil {
  static updateMappingsFromDocuments(cfg: ConfigModel): void {
    // TODO: check this non null operator
    for (const mapping of cfg.mappings!.mappings) {
      MappingUtil.updateMappedFieldsFromDocuments(mapping, cfg, true);
      MappingUtil.updateMappedFieldsFromDocuments(mapping, cfg, false);
    }
    for (const doc of cfg.getAllDocs()) {
      Iif (doc.id == null) {
        doc.id =
          'DOC.' +
          doc.name +
          '.' +
          Math.floor(Math.random() * 1000000 + 1).toString();
      }
    }
  }
 
  static updateMappedFieldsFromDocuments(
    mapping: MappingModel,
    cfg: ConfigModel,
    isSource: boolean
  ): void {
    let mappedFields: MappedField[] = mapping.getMappedFields(isSource);
    let mappedFieldIndex = -1;
 
    for (const mappedField of mappedFields) {
      let doc: DocumentDefinition | null = null;
      mappedFieldIndex += 1;
 
      if (
        mappedField.field instanceof PaddingField ||
        mappedField.mappingField === undefined
      ) {
        continue;
      }
      if (MappingUtil.isPropertyField(mappedField.mappingField)) {
        doc = isSource ? cfg.sourcePropertyDoc : cfg.targetPropertyDoc;
        // Preserve property Document ID from parsed data
        Eif (mappedField.mappingField.docId) {
          doc.id = mappedField.mappingField.docId;
        }
      } else if (MappingUtil.isConstantField(mappedField.mappingField)) {
        doc = cfg.constantDoc;
        // Preserve constant Document ID from parsed data
        Eif (mappedField.mappingField.docId) {
          doc.id = mappedField.mappingField.docId;
        }
      } else {
        Iif (mappedField.mappingField.docId == null) {
          cfg.errorService.addError(
            new ErrorInfo({
              message: `Could not find doc ID for mapped field ${mappedField.mappingField.name}`,
              level: ErrorLevel.ERROR,
              scope: ErrorScope.APPLICATION,
              type: ErrorType.INTERNAL,
            })
          );
          continue;
        }
        doc = cfg.getDocForIdentifier(
          mappedField.mappingField.docId!,
          isSource
        );
        Iif (doc == null) {
          if (mappedField.mappingField.name != null) {
            cfg.errorService.addError(
              new ErrorInfo({
                message: `Could not find document for mapped field '${mappedField.mappingField.name}' \
with ID ${mappedField.mappingField.docId}`,
                level: ErrorLevel.ERROR,
                scope: ErrorScope.APPLICATION,
                type: ErrorType.INTERNAL,
              })
            );
          }
          continue;
        }
 
        doc.id = mappedField.mappingField.docId;
      }
 
      if (!mappedField.mappingField.path) {
        continue;
      }
      mappedField.field = doc.getField(mappedField.mappingField.path);
 
      Iif (mappedField.field == null) {
        // Check for collection instance.
        if (mappedField.mappingField.path.indexOf('<0>') >= 0) {
          mappedField.field = doc.getField(
            mappedField.mappingField.path!.replace('<0>', '<>')
          );
        } else if (
          MappingUtil.isConstantField(mappedField.mappingField) &&
          mappedField.mappingField.value &&
          mappedField.mappingField.fieldType
        ) {
          let constantField = cfg.constantDoc.getField(
            mappedField.mappingField.value
          );
          if (!constantField) {
            constantField = new Field();
          }
          constantField.value = mappedField.mappingField.value;
          constantField.type = mappedField.mappingField.fieldType;
          constantField.displayName = constantField.value;
          constantField.name = constantField.value;
          constantField.path = constantField.value;
          constantField.userCreated = true;
          mappedField.field = constantField;
          doc.addField(constantField);
        } else if (
          MappingUtil.isPropertyField(mappedField.mappingField) &&
          mappedField.mappingField.fieldType &&
          mappedField.mappingField.name &&
          mappedField.mappingField.path
        ) {
          const propMappingField = mappedField.mappingField as IPropertyField;
          let propertyField = doc.getField(propMappingField.path!);
 
          if (!propertyField) {
            propertyField = new Field();
          }
          let fieldName = propMappingField.name;
          propertyField.type = propMappingField.fieldType!;
          if (propMappingField.scope) {
            propertyField.scope = propMappingField.scope;
          }
          propertyField.displayName = fieldName!;
          propertyField.name = fieldName!;
          propertyField.path = propMappingField.path!;
          propertyField.userCreated = true;
          mappedField.field = propertyField;
          doc.addField(propertyField);
        } else {
          cfg.errorService.addError(
            new ErrorInfo({
              message: `Could not find field from document '${doc.name}' for mapped field '${mappedField.mappingField.name}'`,
              level: ErrorLevel.ERROR,
              scope: ErrorScope.APPLICATION,
              type: ErrorType.INTERNAL,
              object: { mappedField: mappedField, doc: doc },
            })
          );
          return;
        }
      }
 
      const zeroBasedIndex = +mappedField.mappingField.index!; // TODO: check this non null operator
      mappedFields = mapping.getMappedFields(isSource);
      if (zeroBasedIndex <= mappedFieldIndex) {
        mappedFields[mappedFieldIndex] = mappedField;
      } else {
        cfg.mappingService.addPlaceholders(
          zeroBasedIndex - mappedFieldIndex,
          mapping,
          mappedFieldIndex,
          isSource
        );
      }
    }
  }
 
  /**
   * Check all mappings in the current context and remove if it refers to un-existing fields.
   *
   * @param cfg ConfigModel
   */
  static removeStaleMappings(cfg: ConfigModel): void {
    let index = 0;
    let sourceFieldPaths: string[] = [];
    for (const doc of cfg.getDocs(true)) {
      sourceFieldPaths = sourceFieldPaths.concat(
        Field.getFieldPaths(doc.getAllFields())
      );
    }
    let targetSourcePaths: string[] = [];
    for (const doc of cfg.getDocs(false)) {
      targetSourcePaths = targetSourcePaths.concat(
        Field.getFieldPaths(doc.getAllFields())
      );
    }
    // TODO: check these non null operator
    while (index < cfg.mappings!.mappings.length) {
      const mapping: MappingModel = cfg.mappings!.mappings[index];
      const mappingIsStale: boolean = this.isMappingStale(
        mapping,
        sourceFieldPaths,
        targetSourcePaths
      );
      Iif (mappingIsStale) {
        cfg.mappings!.mappings.splice(index, 1);
      } else {
        index++;
      }
    }
  }
 
  private static isMappingStale(
    mapping: MappingModel,
    sourceFieldPaths: string[],
    targetSourcePaths: string[]
  ): boolean {
    for (const field of mapping.getFields(true)) {
      Iif (
        !(field instanceof PaddingField) &&
        sourceFieldPaths.indexOf(field.path) === -1
      ) {
        return true;
      }
    }
    for (const field of mapping.getFields(false)) {
      Iif (
        !(field instanceof PaddingField) &&
        targetSourcePaths.indexOf(field.path) === -1
      ) {
        return true;
      }
    }
 
    return false;
  }
 
  static updateDocumentNamespacesFromMappings(cfg: ConfigModel): void {
    const docs: DocumentDefinition[] = cfg.getDocs(false);
 
    // TODO: check this non null operator
    for (const parsedDoc of cfg.mappings!.parsedDocs) {
      Iif (!parsedDoc) {
        continue;
      }
      if (parsedDoc.isSource) {
        continue;
      }
      Eif (parsedDoc.namespaces.length === 0) {
        continue;
      }
 
      const doc = this.getDocById(parsedDoc.id, docs);
      if (doc == null) {
        cfg.errorService.addError(
          new ErrorInfo({
            message: `Could not find document with identifier '${parsedDoc.id}' for namespace override.`,
            level: ErrorLevel.ERROR,
            scope: ErrorScope.APPLICATION,
            type: ErrorType.INTERNAL,
            object: {
              identifier: parsedDoc.id,
              parsedDoc: parsedDoc,
              docs: docs,
            },
          })
        );
        continue;
      }
 
      doc.namespaces = [...parsedDoc.namespaces];
    }
  }
 
  private static getDocById(
    documentId: string,
    docs: DocumentDefinition[]
  ): DocumentDefinition | null {
    if (documentId == null || docs == null || !docs.length) {
      return null;
    }
    for (const doc of docs) {
      if (doc.id === documentId) {
        return doc;
      }
    }
    return null;
  }
 
  static activeMapping(cfg: ConfigModel): boolean {
    return !!cfg?.mappings?.activeMapping;
  }
 
  /**
   * Return true if the specified mapped field array has any established field actions,
   * false otherwise.
   *
   * @param fields
   */
  static hasFieldAction(fields: MappedField[]): boolean {
    for (let field of fields) {
      if (field.actions.length > 0) {
        return true;
      }
    }
    return false;
  }
 
  static hasMappedCollection(
    mapping: MappingModel,
    isSource: boolean
  ): boolean | null {
    const mappedFields = mapping.getMappedFields(isSource);
    return (
      mapping.isFullyMapped() &&
      mappedFields[0].field &&
      mappedFields[0].field.isInCollection()
    );
  }
 
  static isPropertyField(field: IField) {
    return field?.jsonType === PROPERTY_FIELD_JSON_TYPE;
  }
 
  static isConstantField(field: IField) {
    return field?.jsonType === CONSTANT_FIELD_JSON_TYPE;
  }
}