All files / dist/src core.js

95.31% Statements 183/192
86.61% Branches 97/112
98.04% Functions 50/51
95.53% Lines 171/179

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  2x 2x   2x 2x 2x 2x 34x 227x 227x 227x 227x 1793x 1580x           213x   1793x 1793x 1793x 227x 227x 1793x 227x 227x   227x 3611x 3611x     227x 1793x 201x     227x 1793x   227x                               34x 227x 227x   34x 1435x 1435x     1435x   34x 227x 227x   34x 42896x 42896x     42896x   34x 42895x                     34x 188x 39x 1434x 39x 39x   39x 188x 21304x     1246x 1246x 1246x 29445x 28144x 28144x 29445x 28597x   848x 849x 849x 822x     26x       1246x 12590x 10448x   49133x 2142x 1203x   939x   1246x       1246x 6559x 2788x 2788x 6559x 6150x   409x 410x 410x 355x     54x   1246x 614x 75x 75x             539x 539x   539x 61x 61x       1110x 761x   349x 228x 228x 149x     79x 79x             121x   121x       989x     39x                                         34x 22x 22x 22x 188x 188x   188x 149x     39x   188x   22x   34x 188x 1434x 1434x 6747x 6747x               6747x 6747x   1434x             34x 188x 6747x 6747x 6747x     6747x 6747x 6747x     34x 22x 22x 22x 22x 22x 39x 22x 22x   34x 4x 2x     2x   2x   34x 5x 1x   4x 4x     4x 2x   2x   34x 3x 1x   2x   34x 3x 1x   2x   34x                 227x     227x       2x  
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCore = void 0;
const camelcase_1 = __importDefault(require("camelcase"));
const createCore = ({ entities: externalEntities }) => {
    const entities = externalEntities.map((d) => {
        const tableName = d.tableName;
        const displayName = d.displayName || (0, camelcase_1.default)(d.tableName);
        const collectionDisplayName = d.collectionDisplayName || `${displayName}s`;
        const columns = (typeof d.columns === 'function' ? d.columns() : d.columns).map((d) => {
            if (typeof d === 'string') {
                return {
                    column: d,
                    property: (0, camelcase_1.default)(d),
                    primaryKey: false
                };
            }
            return Object.assign({ column: d.column, property: d.property || (0, camelcase_1.default)(d.column), primaryKey: d.primaryKey || false }, (d.references ? { references: d.references } : {}));
        });
        const propertyNames = columns.map((x) => x.property);
        const columnNames = columns.map((x) => x.column);
        const prefixedColumnNames = columnNames.map((col) => `${tableName}#${col}`);
        const Model = d.Model;
        const Collection = d.Collection;
        const pkColumnsData = columns.filter((x) => x.primaryKey);
        const _primaryKeys = pkColumnsData.map((x) => x.column);
        const primaryKeys = _primaryKeys.length > 0 ? _primaryKeys : ['id'];
        // Returns unique identifier of model (the values of the primary keys)
        const getPkId = (model) => {
            return primaryKeys
                .map((key) => model[key])
                .join('');
        };
        const references = columns
            .filter((x) => x.references)
            .reduce((accum, item) => Object.assign({}, accum, {
            [item.property]: item.references
        }), {});
        const selectColumnsClause = prefixedColumnNames
            .map((prefixed, index) => `"${tableName}".${columnNames[index]} as "${prefixed}"`)
            .join(', ');
        return {
            tableName,
            displayName,
            collectionDisplayName,
            columns,
            propertyNames,
            Model,
            Collection,
            columnNames,
            prefixedColumnNames,
            primaryKeys,
            references,
            selectColumnsClause,
            getPkId
        };
    });
    const tableNameToEntityMap = entities.reduce((map, entity) => {
        map.set(entity.tableName, entity);
        return map;
    }, new Map());
    const getEntityByTableName = (tableName) => {
        const entity = tableNameToEntityMap.get(tableName);
        Iif (!entity) {
            throw new Error(`Could not find entity for table ${tableName}`);
        }
        return entity;
    };
    const modelToEntityMap = entities.reduce((map, entity) => {
        map.set(entity.Model, entity);
        return map;
    }, new Map());
    const getEntityByModelClass = (Model) => {
        const entity = modelToEntityMap.get(Model);
        Iif (!entity) {
            throw new Error(`Could not find entity for class ${Model}`);
        }
        return entity;
    };
    const getEntityByModel = (model) => {
        return getEntityByModelClass(model.constructor);
    };
    /*
     * 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}]
     */
    const nestClump = (clump) => {
        clump = clump.map((x) => Object.values(x));
        const root = clump[0][0];
        clump = clump.map((row) => row.filter((item, index) => index !== 0));
        const built = { [getEntityByModel(root).displayName]: root };
        let nodes = [root];
        // Wowzer is this both CPU and Memory inefficient
        clump.forEach((array) => {
            array.forEach((_model) => {
                const nodeAlreadySeen = nodes.find((x) => x.constructor.name === _model.constructor.name &&
                    getEntityByModel(x).getPkId(x) ===
                        getEntityByModel(_model).getPkId(_model));
                const model = nodeAlreadySeen || _model;
                const isNodeAlreadySeen = !!nodeAlreadySeen;
                const nodePointingToIt = nodes.find((node) => {
                    const indexes = Object.values(getEntityByModel(node).references)
                        .map((x, i) => x === model.constructor ? i : null)
                        .filter((x, i) => x != null);
                    if (!indexes.length) {
                        return false;
                    }
                    for (const index of indexes) {
                        const property = Object.keys(getEntityByModel(node).references)[index];
                        if (node[property] === model.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) || 0;
                const parentHeirarchy = [
                    root,
                    ...nodes.slice(0, indexOfOldestParent + 1).reverse()
                ];
                const nodeItPointsTo = parentHeirarchy.find((parent) => {
                    const indexes = Object.values(getEntityByModel(model).references)
                        .map((x, i) => x === parent.constructor ? i : null)
                        .filter((x, i) => x != null);
                    if (!indexes.length) {
                        return false;
                    }
                    for (const index of indexes) {
                        const property = Object.keys(getEntityByModel(model).references)[index];
                        if (model[property] === parent.id) {
                            return true;
                        }
                    }
                    return false;
                });
                if (isNodeAlreadySeen) {
                    if (nodeItPointsTo && !nodePointingToIt) {
                        nodes = [model, ...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 = model[getEntityByModel(nodePointingToIt)
                            .collectionDisplayName];
                        if (ec && ec.models.find((m) => m === nodePointingToIt)) {
                            nodes = [model, ...nodes];
                            return;
                        }
                    }
                }
                if (nodePointingToIt) {
                    nodePointingToIt[getEntityByModel(model).displayName] = model;
                }
                else if (nodeItPointsTo) {
                    let collection = nodeItPointsTo[getEntityByModel(model).collectionDisplayName];
                    if (collection) {
                        collection.models.push(model);
                    }
                    else {
                        const Collection = getEntityByModel(model).Collection;
                        nodeItPointsTo[getEntityByModel(model).collectionDisplayName] =
                            new Collection({
                                models: [model]
                            });
                    }
                }
                else {
                    Eif (!getEntityByModel(model).getPkId(model)) {
                        // If the join is fruitless; todo: add a test for this path
                        return;
                    }
                    throw Error(`Could not find how this BO fits: ${JSON.stringify(model)} ${getEntityByModel(model).tableName}`);
                }
                nodes = [model, ...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}]
     *    ]
     *  ]
     */
    const clumpIntoGroups = (processed) => {
        const root = processed[0][0];
        const rootBo = root.constructor;
        const clumps = processed.reduce((accum, item) => {
            const id = getEntityByModel(root)
                .primaryKeys.map((key) => { var _a; return (_a = item.find((x) => x.constructor === rootBo)) === null || _a === void 0 ? void 0 : _a[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()];
    };
    const mapToBos = (objectified) => {
        return Object.keys(objectified).map((tableName) => {
            const entity = getEntityByTableName(tableName);
            const propified = Object.keys(objectified[tableName]).reduce((obj, column) => {
                let propertyName = entity.propertyNames[entity.columnNames.indexOf(column)];
                Iif (!propertyName) {
                    if (column.startsWith('meta_')) {
                        propertyName = (0, camelcase_1.default)(column);
                    }
                    else {
                        throw Error(`No property name for "${column}" in business object "${entity.displayName}". Non-spec'd columns must begin with "meta_".`);
                    }
                }
                obj[propertyName] = objectified[tableName][column];
                return obj;
            }, {});
            return new entity.Model(propified);
        });
    };
    /*
     * Make objects (based on special table#column names) from flat database
     * return value.
     */
    const objectifyDatabaseResult = (result) => {
        return Object.keys(result).reduce((obj, text) => {
            const tableName = text.split('#')[0];
            const column = text.split('#')[1];
            Iif (!tableName || !column) {
                throw new Error('Column names must be namespaced to table');
            }
            obj[tableName] = obj[tableName] || {};
            obj[tableName][column] = result[text];
            return obj;
        }, {});
    };
    const createFromDatabase = (rows) => {
        const result = Array.isArray(rows) ? rows : [rows];
        const objectified = result.map(objectifyDatabaseResult);
        const boified = objectified.map(mapToBos);
        const clumps = clumpIntoGroups(boified);
        const nested = clumps.map(nestClump);
        const models = nested.map((n) => Object.values(n)[0]);
        const Collection = getEntityByModel(models[0]).Collection;
        return new Collection({ models });
    };
    const createAnyFromDatabase = (rows, rootKey) => {
        if (!rows || !rows.length) {
            const Collection = typeof rootKey === 'string'
                ? getEntityByTableName(rootKey).Collection
                : getEntityByModelClass(rootKey).Collection;
            return new Collection({ models: [] });
        }
        return createFromDatabase(rows);
    };
    const createOneFromDatabase = (rows) => {
        if (!rows || !rows.length) {
            throw Error('Did not get one.');
        }
        const collection = createFromDatabase(rows);
        Iif (!collection || !collection.models || collection.models.length === 0) {
            throw Error('Did not get one.');
        }
        else if (collection.models.length > 1) {
            throw Error('Got more than one.');
        }
        return collection.models[0];
    };
    const createOneOrNoneFromDatabase = (rows) => {
        if (!rows || !rows.length) {
            return void 0;
        }
        return createOneFromDatabase(rows);
    };
    const createManyFromDatabase = (rows) => {
        if (!rows || !rows.length) {
            throw Error('Did not get at least one.');
        }
        return createFromDatabase(rows);
    };
    return {
        getEntityByModel,
        getEntityByTableName,
        createFromDatabase,
        createAnyFromDatabase,
        createOneFromDatabase,
        createOneOrNoneFromDatabase,
        createManyFromDatabase,
        tables: entities.reduce((accum, data) => {
            accum[data.displayName] = {
                columns: data.selectColumnsClause
            };
            return accum;
        }, {})
    };
};
exports.createCore = createCore;