All files / src/bo base-bo.js

63.69% Statements 114/179
66.67% Branches 54/81
54.67% Functions 41/75
62.5% Lines 105/168

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 3801x   1x 8x   1117x       14693x 2490x       3703x 40534x         40534x       34347x 223605x     32245x               1291x                                         111x   3703x 3703x 3703x 3703x 3703x         111x 10197x 1104x     1104x   3703x 3703x                     3703x 3703x       1104x                                               13x 111x 111x   111x 85x   26x   111x   13x                         111x 26x 1104x 26x   26x     26x 111x 993x   18827x     993x 993x 993x 27484x 26688x 26688x 27484x 26812x   672x 673x 673x 646x     26x       993x 11737x 9876x   1861x 48580x   1861x 963x   898x   993x       993x 5858x     5858x 5526x   332x 332x   993x 538x 75x 75x             463x 463x 61x 61x     857x 585x 272x 151x 151x 85x   66x         121x   121x           736x       26x       13x 13x 13x 13x 13x 26x 13x       4x 4x   4x     4x                                                                                                                                                                                                                                 2379x   2379x        
const camelCase = require('camelcase');
 
module.exports = ({ getBusinessObjects }) =>
  class Base {
    constructor(props) {
      Object.assign(this, props);
    }
 
    static primaryKey() {
      const primaryKey = this.sqlColumnsData.filter(x => x.primaryKey);
      return primaryKey.length > 0 ? primaryKey : ['id'];
    }
 
    static get columns() {
      return this.sqlColumnsData.map(
        x => x.property || camelCase(x.column || x)
      );
    }
 
    static get sqlColumns() {
      return this.sqlColumnsData.map(x => x.column || x);
    }
 
    static get references() {
      return this.sqlColumnsData
        .filter(x => x.references)
        .reduce(
          (accum, item) =>
            Object.assign({}, accum, {
              [item.property || camelCase(item.column || item)]: item.references
            }),
          {}
        );
    }
 
    static get displayName() {
      return camelCase(this.tableName);
    }
 
    static getPrefixedColumnNames() {
      return this.sqlColumns.map(col => `${this.tableName}#${col}`);
    }
 
    static getSQLSelectClause() {
      return this.getPrefixedColumnNames()
        .map(
          (prefixed, index) =>
            `"${this.tableName}".${this.sqlColumns[index]} as "${prefixed}"`
        )
        .join(', ');
    }
 
    /*
     * Make objects (based on special table#column names) from flat database
     * return value.
     */
    static objectifyDatabaseResult(result) {
      return Object.keys(result).reduce((obj, text) => {
        const tableName =
          text.indexOf('#') > -1 ? text.split('#')[0] : this.tableName;
        const column = text.indexOf('#') > -1 ? text.split('#')[1] : text;
        obj[tableName] = obj[tableName] || {};
        obj[tableName][column] = result[text];
        return obj;
      }, {});
    }
 
    static mapToBos(objectified) {
      return Object.keys(objectified).map(tableName => {
        const Bo = getBusinessObjects().find(bo => bo.tableName === tableName);
        Iif (!Bo) {
          throw Error(`No business object with table name "${tableName}"`);
        }
        const propified = Object.keys(objectified[tableName]).reduce(
          (obj, column) => {
            let propertyName = Bo.columns[Bo.sqlColumns.indexOf(column)];
            Iif (!propertyName) {
              if (column.startsWith('meta_')) {
                propertyName = camelCase(column);
              } else {
                throw Error(
                  `No property name for "${column}" in business object "${
                    Bo.displayName
                  }". Non-spec'd columns must begin with "meta_".`
                );
              }
            }
            obj[propertyName] = objectified[tableName][column];
            return obj;
          },
          {}
        );
        return new Bo(propified);
      });
    }
 
    /*
     * 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}]
     *    ]
     *  ]
     */
    static clumpIntoGroups(processed) {
      const clumps = processed.reduce((accum, item) => {
        const id = this.primaryKey()
          .map(key => item.find(x => x.constructor === this)[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()];
    }
 
    /*
     * 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}]
     */
    static nestClump(clump) {
      clump = clump.map(x => Object.values(x)); // clump wasn't actually what I have documented
      const root = clump[0][0];
      clump = clump.map(row => row.filter((item, index) => index !== 0));
      const built = { [root.constructor.displayName]: root };
 
      let nodes = [root];
 
      // Wowzer is this both CPU and Memory inefficient
      clump.forEach(array => {
        array.forEach(_bo => {
          const nodeAlreadySeen = nodes.find(
            x =>
              x.constructor.name === _bo.constructor.name &&
              x.getId() === _bo.getId()
          );
          const bo = nodeAlreadySeen || _bo;
          const isNodeAlreadySeen = !!nodeAlreadySeen;
          const nodePointingToIt = nodes.find(node => {
            const indexes = Object.values(node.constructor.references)
              .map((x, i) => (x === bo.constructor ? i : null))
              .filter(x => x != null);
            if (!indexes.length) {
              return false;
            }
            for (const index of indexes) {
              const property = Object.keys(node.constructor.references)[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, obj) => {
            if (answer != null) {
              return answer;
            }
            const index = nodes.findIndex(
              n => n.constructor === obj.constructor
            );
            if (index !== -1) {
              return index;
            }
            return null;
          }, null);
          const parentHeirarchy = [
            root,
            ...nodes.slice(0, indexOfOldestParent + 1).reverse()
          ];
          const nodeItPointsTo = parentHeirarchy.find(parent => {
            const index = Object.values(bo.constructor.references).indexOf(
              parent.constructor
            );
            if (index === -1) {
              return false;
            }
            const property = Object.keys(bo.constructor.references)[index];
            return bo[property] === 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).
            const ec = bo[nodePointingToIt.BoCollection.displayName];
            if (ec && ec.models.find(m => m === nodePointingToIt)) {
              nodes = [bo, ...nodes];
              return;
            }
          }
          if (nodePointingToIt) {
            nodePointingToIt[bo.constructor.displayName] = bo;
          } else if (nodeItPointsTo) {
            let collection = nodeItPointsTo[bo.BoCollection.displayName];
            if (collection) {
              collection.models.push(bo);
            } else {
              nodeItPointsTo[bo.BoCollection.displayName] = new bo.BoCollection(
                { models: [bo] }
              );
            }
          } else {
            Eif (!bo.getId()) {
              // 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;
    }
 
    static createFromDatabase(_result) {
      const result = Array.isArray(_result) ? _result : [_result];
      const objectified = result.map(this.objectifyDatabaseResult.bind(this));
      const boified = objectified.map(this.mapToBos.bind(this));
      const clumps = this.clumpIntoGroups(boified);
      const nested = clumps.map(this.nestClump.bind(this));
      const models = nested.map(n => Object.values(n)[0]);
      return new new this().BoCollection({ models });
    }
 
    static createOneFromDatabase(_result) {
      const collection = this.createFromDatabase(_result);
      Iif (collection.models.length > 1) {
        throw Error('Got more than one.');
      } else Iif (collection.models.length === 0) {
        throw Error('Did not get one.');
      }
      return collection.models[0];
    }
 
    static createOneOrNoneFromDatabase(_result) {
      if (!_result) {
        return _result;
      }
      const collection = this.createFromDatabase(_result);
      if (collection.models.length > 1) {
        throw Error('Got more than one.');
      }
      return collection.models[0];
    }
 
    static createManyFromDatabase(_result) {
      const collection = this.createFromDatabase(_result);
      if (collection.models.length === 0) {
        throw Error('Did not get at least one.');
      }
      return collection;
    }
 
    getSqlInsertParts() {
      const columns = this.constructor.sqlColumns
        .filter(
          (column, index) => this[this.constructor.columns[index]] !== void 0
        )
        .map(col => `"${col}"`)
        .join(', ');
      const values = this.constructor.columns
        .map(column => this[column])
        .filter(value => value !== void 0);
      const valuesVar = values.map((value, index) => `$${index + 1}`);
      return { columns, values, valuesVar };
    }
 
    getSqlUpdateParts(on = 'id') {
      const clauseArray = this.constructor.sqlColumns
        .filter(
          (sqlColumn, index) => this[this.constructor.columns[index]] !== void 0
        )
        .map((sqlColumn, index) => `"${sqlColumn}" = $${index + 1}`);
      const clause = clauseArray.join(', ');
      const idVar = `$${clauseArray.length + 1}`;
      const _values = this.constructor.columns
        .map(column => this[column])
        .filter(value => value !== void 0);
      const values = [..._values, this[on]];
      return { clause, idVar, values };
    }
 
    getMatchingParts() {
      const whereClause = this.constructor.columns
        .map((col, index) =>
          this[col] != null
            ? `"${this.constructor.tableName}"."${
                this.constructor.sqlColumns[index]
              }"`
            : null
        )
        .filter(x => x != null)
        .map((x, i) => `${x} = $${i + 1}`)
        .join(' AND ');
      const values = this.constructor.columns
        .map(col => (this[col] != null ? this[col] : null))
        .filter(x => x != null);
      return { whereClause, values };
    }
 
    // This one returns an object, which allows it to be more versatile.
    // Todo: make this one even better and use it instead of the one above.
    getMatchingPartsObject() {
      const whereClause = this.constructor.columns
        .map((col, index) =>
          this[col] != null
            ? `"${this.constructor.tableName}"."${
                this.constructor.sqlColumns[index]
              }"`
            : null
        )
        .filter(x => x != null)
        .map((x, i) => `${x} = $(${i + 1})`)
        .join(' AND ');
      const values = this.constructor.columns
        .map(col => (this[col] != null ? this[col] : null))
        .filter(x => x != null)
        .reduce(
          (accum, val, index) => Object.assign({}, accum, { [index + 1]: val }),
          {}
        );
      return { whereClause, values };
    }
 
    getNewWith(sqlColumns, values) {
      const Constructor = this.constructor;
      const boKeys = sqlColumns.map(
        key => Constructor.columns[Constructor.sqlColumns.indexOf(key)]
      );
      const boData = boKeys.reduce((data, key, index) => {
        data[key] = values[index];
        return data;
      }, {});
      return new Constructor(boData);
    }
 
    getValueBySqlColumn(sqlColumn) {
      return this[
        this.constructor.columns[this.constructor.sqlColumns.indexOf(sqlColumn)]
      ];
    }
 
    // Returns unique identifier of bo (the values of the primary keys)
    getId() {
      return this.constructor
        .primaryKey()
        .map(key => this[key])
        .join('');
    }
  };