All files business-object.ts

69.57% Statements 144/207
63.74% Branches 58/91
58.44% Functions 45/77
68.56% Lines 133/194

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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 4082x                                                     2x 14693x 2490x 2490x     2x 40534x     2x 44884x     2x 34542x 225928x     32999x             2x 1346x     2x       2x 681x       2x 333x     2x 55x     333x           2x 2379x 2379x                         2x 111x 26x 26x 111x 1104x     26x   26x     26x 111x 993x   18827x   993x 993x 993x 27484x 26688x 26688x 27484x 26812x   672x 673x 673x 646x     26x       993x 11737x 9590x   49677x 2147x 1047x   1100x   993x       993x 6011x     6011x 5637x   374x 374x   993x 538x 75x 75x             463x 463x 463x 62x 62x       856x 584x 272x 151x 151x 84x   67x         121x   121x       735x       26x                                           2x 13x 13x 111x 111x   111x 85x   26x   111x   13x     2x 111x 10197x 1104x     1104x   3703x 3703x                     3703x 3703x       1104x               2x 111x 3703x 3703x 3703x 3703x 3703x       2x 13x 13x 111x 13x 13x 26x 13x     2x 4x 4x   4x     4x     2x                     2x               2x                           2x                             2x                                       2x                                           2x                       2x              
const camelCase = require('camelcase');
 
export interface ColumnDataObject {
  column: string;
  property?: string;
  references?: EntityConstructor;
  primaryKey?: boolean;
}
export type ColumnData = ColumnDataObject & string;
 
export abstract class Entity {
  static readonly tableName: string;
  static readonly sqlColumnsData: Array<ColumnData>;
  static readonly displayName?: string;
  readonly BoCollection!: EntityCollectionConstructor;
  [key:string]: any;
}
export type EntityConstructor = (new (props: object) => Entity) & Omit<typeof Entity, never>;
 
export abstract class EntityCollection {
  static readonly Bo: EntityConstructor;
  static readonly displayName?: string;
  abstract models: Array<Entity>;
}
export type EntityCollectionConstructor = (new (props: object) => Entity) & Omit<typeof Entity, never>;
 
 
export const getPrimaryKey = (Bo: EntityConstructor): Array<string> => {
  const pkColumnsData = Bo.sqlColumnsData.filter((x: ColumnData) => x.primaryKey);
  const primaryKeys = pkColumnsData.map((x: ColumnData) => x.column);
  return primaryKeys.length > 0 ? primaryKeys : ['id'];
};
 
export const getProperties = (Bo: EntityConstructor): Array<string> => {
  return Bo.sqlColumnsData.map((x: ColumnData): string => x.property || camelCase(x.column || x));
};
 
export const getSqlColumns = (Bo: EntityConstructor): Array<string> => {
  return Bo.sqlColumnsData.map((x: ColumnData): string => x.column || x);
};
 
export const getReferences = (Bo: EntityConstructor): object => {
  return Bo.sqlColumnsData
    .filter((x: ColumnData) => x.references)
    .reduce(
      (accum: any, item: ColumnData) =>
        Object.assign({}, accum, {
          [item.property || camelCase(item.column || item)]: item.references
        }),
      {}
    );
};
 
export const getDisplayName = (Bo: EntityConstructor): string => {
  return camelCase(Bo.tableName);
};
 
export const getTableName = (bo: Entity): string => {
  return (bo.constructor as EntityConstructor).tableName;
};
 
export const getCollectionDisplayName = (bo: Entity): string => {
  return (bo.BoCollection).displayName
    || `${getDisplayName(bo.constructor as EntityConstructor)}s`;
};
 
export const getPrefixedColumnNames = (Bo: EntityConstructor): Array<string> => {
  return getSqlColumns(Bo).map((col: string) => `${Bo.tableName}#${col}`);
};
 
export const getColumns = (Bo: EntityConstructor): string => {
  return getPrefixedColumnNames(Bo)
    .map(
      (prefixed: string, index: number) =>
        `"${Bo.tableName}".${getSqlColumns(Bo)[index]} as "${prefixed}"`
    )
    .join(', ');
};
 
// Returns unique identifier of bo (the values of the primary keys)
export const getId = (bo: Entity): string => {
  return getPrimaryKey(bo.constructor as EntityConstructor)
    .map((key: string) => bo[key as keyof typeof bo])
    .join('');
};
 
/*
 * In:
 *  [
 *    [Article {id: 32}, ArticleTag {id: 54}]
 *    [Article {id: 32}, ArticleTag {id: 55}]
 *  ]
 * Out:
 *  Article {id: 32, ArticleTags articleTags: [ArticleTag {id: 54}, ArticleTag {id: 55}]
 */
export const nestClump = (clump: Array<Array<Entity>>): object => {
  clump = clump.map((x: Array<Entity>) => Object.values(x));
  const root = clump[0][0];
  clump = clump.map(
    (row: Array<Entity>) => row.filter(
      (item: Entity, index: number) => index !== 0
    )
  );
  const built = { [getDisplayName(root.constructor as EntityConstructor)]: root };
 
  let nodes = [root];
 
  // Wowzer is this both CPU and Memory inefficient
  clump.forEach((array: Array<Entity>) => {
    array.forEach((_bo: Entity) => {
      const nodeAlreadySeen = nodes.find(
        (x: Entity) =>
          x.constructor.name === _bo.constructor.name && getId(x) === getId(_bo)
      );
      const bo = nodeAlreadySeen || _bo;
      const isNodeAlreadySeen = !!nodeAlreadySeen;
      const nodePointingToIt = nodes.find(node => {
        const indexes = Object.values(getReferences(node.constructor as EntityConstructor))
          .map((x: EntityConstructor, i: number) => (x === bo.constructor ? i : null))
          .filter((x: number | null, i) => x != null) as Array<number>;
        if (!indexes.length) {
          return false;
        }
        for (const index of indexes) {
          const property = Object.keys(getReferences(node.constructor as EntityConstructor))[index];
          if (node[property] === bo.id) {
            return true;
          }
        }
        return false;
      });
      // For first obj type which is has an instance in nodes array,
      // get its index in nodes array
      const indexOfOldestParent = array.reduce((answer: number, obj: Entity) => {
        if (answer != 0) {
          return answer;
        }
        const index = nodes.findIndex(n => n.constructor === obj.constructor);
        if (index !== -1) {
          return index;
        }
        return 0;
      }, 0);
      const parentHeirarchy = [
        root,
        ...nodes.slice(0, indexOfOldestParent + 1).reverse()
      ];
      const nodeItPointsTo = parentHeirarchy.find(parent => {
        const index = Object.values(getReferences(bo.constructor as EntityConstructor)).indexOf(
          parent.constructor
        );
        if (index === -1) {
          return false;
        }
        const property = Object.keys(getReferences(bo.constructor as EntityConstructor))[index];
        return bo[property as keyof typeof bo] === parent.id;
      });
      if (isNodeAlreadySeen) {
        if (nodeItPointsTo && !nodePointingToIt) {
          nodes = [bo, ...nodes];
          return;
        }
        // If the nodePointingToIt (eg, parcel_event) is part of an
        // existing collection on this node (eg, parcel) which is a
        // nodeAlreadySeen, early return so we don't create it (parcel) on
        // the nodePointingToIt (parcel_event), since it (parcel) has been
        // shown to be the parent (of parcel_events).
        Eif (nodePointingToIt) {
          const ec = bo[getCollectionDisplayName(nodePointingToIt) as keyof typeof bo];
          if (ec && ec.models.find((m: Entity) => m === nodePointingToIt)) {
            nodes = [bo, ...nodes];
            return;
          }
        }
      }
      if (nodePointingToIt) {
        nodePointingToIt[getDisplayName(bo.constructor as EntityConstructor)] = bo;
      } else if (nodeItPointsTo) {
        let collection = nodeItPointsTo[getCollectionDisplayName(bo)];
        if (collection) {
          collection.models.push(bo);
        } else {
          nodeItPointsTo[getCollectionDisplayName(bo)] = new bo.BoCollection({
            models: [bo]
          });
        }
      } else {
        Eif (!getId(bo)) {
          // If the join is fruitless; todo: add a test for this path
          return;
        }
        throw Error(`Could not find how this BO fits: ${JSON.stringify(bo)}`);
      }
      nodes = [bo, ...nodes];
    });
  });
 
  return built;
};
 
/*
 * Clump array of flat objects into groups based on id of root
 * In:
 *  [
 *    [Article {id: 32}, ArticleTag {id: 54}]
 *    [Article {id: 32}, ArticleTag {id: 55}]
 *    [Article {id: 33}, ArticleTag {id: 56}]
 *  ]
 * Out:
 *  [
 *    [
 *      [Article {id: 32}, ArticleTag {id: 54}]
 *      [Article {id: 32}, ArticleTag {id: 55}]
 *    ]
 *    [
 *      [Article {id: 33}, ArticleTag {id: 56}]
 *    ]
 *  ]
 */
export const clumpIntoGroups = (processed: Array<Array<Entity>>): Array<Array<Array<Entity>>> => {
  const rootBo = processed[0][0].constructor;
  const clumps = processed.reduce((accum: any, item: Array<Entity>) => {
    const id = getPrimaryKey(rootBo as EntityConstructor)
      .map((key: string) => item.find((x: Entity) => x.constructor === rootBo)?.[key])
      .join('@');
    if (accum.has(id)) {
      accum.set(id, [...accum.get(id), item]);
    } else {
      accum.set(id, [item]);
    }
    return accum;
  }, new Map());
  return [...clumps.values()];
};
 
export const mapToBos = (objectified: any, getBusinessObjects: () => Array<EntityConstructor>) => {
  return Object.keys(objectified).map(tableName => {
    const Bo = getBusinessObjects().find((Bo: EntityConstructor) => Bo.tableName === tableName);
    Iif (!Bo) {
      throw Error(`No business object with table name "${tableName}"`);
    }
    const propified = Object.keys(objectified[tableName]).reduce(
      (obj: any, column) => {
        let propertyName = getProperties(Bo)[getSqlColumns(Bo).indexOf(column)];
        Iif (!propertyName) {
          if (column.startsWith('meta_')) {
            propertyName = camelCase(column);
          } else {
            throw Error(
              `No property name for "${column}" in business object "${getDisplayName(
                Bo
              )}". Non-spec'd columns must begin with "meta_".`
            );
          }
        }
        obj[propertyName] = objectified[tableName][column];
        return obj;
      },
      {}
    );
    return new Bo(propified);
  });
};
 
/*
 * Make objects (based on special table#column names) from flat database
 * return value.
 */
export const objectifyDatabaseResult = (result: object) => {
  return Object.keys(result).reduce((obj: any, text: string) => {
    const tableName = text.split('#')[0];
    const column = text.split('#')[1];
    obj[tableName] = obj[tableName] || {};
    obj[tableName][column] = result[text as keyof typeof result];
    return obj;
  }, {});
};
 
export const createFromDatabase = (_result: Array<object> | object, getBusinessObjects: () => Array<EntityConstructor>) => {
  const result = Array.isArray(_result) ? _result : [_result];
  const objectified = result.map(objectifyDatabaseResult);
  const boified = objectified.map((x: any) => mapToBos(x, getBusinessObjects));
  const clumps = clumpIntoGroups(boified);
  const nested = clumps.map(nestClump);
  const models = nested.map(n => Object.values(n)[0]);
  return models.length ? new models[0].BoCollection({ models }) : void 0;
};
 
export const createOneFromDatabase = (_result: any, getBusinessObjects: () => Array<EntityConstructor>) => {
  const collection = createFromDatabase(_result, getBusinessObjects);
  Iif (!collection || collection.models.length === 0) {
    throw Error('Did not get one.');
  } else Iif (collection.models.length > 1) {
    throw Error('Got more than one.');
  }
  return collection.models[0];
};
 
export const createOneOrNoneFromDatabase = (_result: any, getBusinessObjects: () => Array<EntityConstructor>) => {
  if (!_result) {
    return _result;
  }
  const collection = createFromDatabase(_result, getBusinessObjects);
  if (collection && collection.models.length > 1) {
    throw Error('Got more than one.');
  }
  return collection && collection.models[0];
};
 
export const createManyFromDatabase = (_result: any, getBusinessObjects: () => Array<EntityConstructor>) => {
  const collection = createFromDatabase(_result, getBusinessObjects);
  if (!collection || collection.models.length === 0) {
    throw Error('Did not get at least one.');
  }
  return collection;
};
 
export const getSqlInsertParts = (bo: Entity) => {
  const columns = getSqlColumns(bo.constructor as EntityConstructor)
    .filter(
      (column: string, index: number) => bo[getProperties(bo.constructor as EntityConstructor)[index] as keyof typeof bo] !== void 0
    )
    .map((col: string) => `"${col}"`)
    .join(', ');
  const values = getProperties(bo.constructor as EntityConstructor)
    .map((property: string) => bo[property as keyof typeof bo])
    .filter((value: any) => value !== void 0);
  const valuesVar = values.map((value: any, index: number) => `$${index + 1}`);
  return { columns, values, valuesVar };
};
 
export const getSqlUpdateParts = (bo: Entity, on = 'id') => {
  const clauseArray = getSqlColumns(bo.constructor as EntityConstructor)
    .filter(
      (sqlColumn: string, index: number) => bo[getProperties(bo.constructor as EntityConstructor)[index] as keyof typeof bo] !== void 0
    )
    .map((sqlColumn: string, index: number) => `"${sqlColumn}" = $${index + 1}`);
  const clause = clauseArray.join(', ');
  const idVar = `$${clauseArray.length + 1}`;
  const _values = getProperties(bo.constructor as EntityConstructor)
    .map((property: string) => bo[property as keyof typeof bo])
    .filter((value: any) => value !== void 0);
  const values = [..._values, bo[on as keyof typeof bo]];
  return { clause, idVar, values };
};
 
export const getMatchingParts = (bo: Entity) => {
  const whereClause = getProperties(bo.constructor as EntityConstructor)
    .map((property: string, index: number) =>
      bo[property as keyof typeof bo] != null
        ? `"${(bo.constructor as EntityConstructor).tableName}"."${
            getSqlColumns(bo.constructor as EntityConstructor)[index]
          }"`
        : null
    )
    .filter((x: string | null) => x != null)
    .map((x: string | null, i: number) => `${x} = $${i + 1}`)
    .join(' AND ');
  const values = getProperties(bo.constructor as EntityConstructor)
    .map((property: string) => (bo[property as keyof typeof bo] != null ? bo[property as keyof typeof bo] : null))
    .filter((x: any) => x != null);
  return { whereClause, values };
};
 
// This one returns an object, which allows it to be more versatile.
// To-do: make this one even better and use it instead of the one above.
export const getMatchingPartsObject = (bo: Entity) => {
  const whereClause = getProperties(bo.constructor as EntityConstructor)
    .map((property: string, index: number) =>
      bo[property as keyof typeof bo] != null
        ? `"${(bo.constructor as EntityConstructor).tableName}"."${
            getSqlColumns(bo.constructor as EntityConstructor)[index]
          }"`
        : null
    )
    .filter((x: string | null) => x != null)
    .map((x: string | null, i: number) => `${x} = $(${i + 1})`)
    .join(' AND ');
  const values = getProperties(bo.constructor as EntityConstructor)
    .map((property: string) => (bo[property as keyof typeof bo] != null ? bo[property as keyof typeof bo] : null))
    .filter((x: any) => x != null)
    .reduce(
      (accum: any, val: any, index: number) => Object.assign({}, accum, { [index + 1]: val }),
      {}
    );
  return { whereClause, values };
};
 
export const getNewWith = (bo: Entity, sqlColumns: any, values: any) => {
  const Constructor = bo.constructor as any;
  const boKeys = sqlColumns.map(
    (key: string) => getProperties(Constructor)[getSqlColumns(Constructor).indexOf(key)]
  );
  const boData = boKeys.reduce((data: any, key: string, index: number) => {
    data[key] = values[index];
    return data;
  }, {});
  return new Constructor(boData);
};
 
export const getValueBySqlColumn = (bo: Entity, sqlColumn: string) => {
  return bo[
    getProperties(bo.constructor as EntityConstructor)[
      getSqlColumns(bo.constructor as EntityConstructor).indexOf(sqlColumn)
    ] as keyof typeof bo
  ];
};