All files / mobx-decorated-models/lib collection.js

90.48% Statements 19/21
68.75% Branches 11/16
100% Functions 4/4
90.48% Lines 19/21

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                  72x 24x 24x   24x 17x   24x 24x 30x                                         24x           84x 84x 84x 72x   84x 53x 41x   12x 12x           84x    
import { observable } from 'mobx';
 
import { findModel } from './model-lookup';
import { setupModel } from './setup-model';
 
function onCollectionChangeInterceptor(
    { modelClass, model, defaults: defaultAttributes, inverseOf },
    parentModel, parentModelProp,
) {
    return (change) => {
        Eif (!change.newValue) {
            change.newValue = {};
        }
        if (!modelClass) {
            modelClass = findModel(model, parentModelProp);
        }
        Eif ('splice' === change.type) {
            for (let i = 0; i < change.added.length; i += 1) {
                change.added[i] = setupModel({
                    attrs: change.added[i],
                    array: change.object,
                    modelClass,
                    defaultAttributes,
                    inverseOf,
                    parentModel,
                    parentModelProp,
                });
            }
        } else if ('update' === change.type) {
            change.newValue = setupModel({
                attrs: change.newValue,
                array: change.object,
                modelClass,
                defaultAttributes,
                inverseOf,
                parentModel,
                parentModelProp,
            });
        }
        return change;
    };
}
 
 
export default function createCollection(options, parentModel, parentModelProp) {
    const ary = observable.array([]);
    Eif (options) {
        if (options.model) {
            ary.intercept(onCollectionChangeInterceptor(options, parentModel, parentModelProp));
        }
        if (options.extend) {
            if ('function' === typeof options.extend) {
                options.extend(ary);
            } else {
                Object.keys(options.extend).forEach((k) => {
                    Object.defineProperty(ary, k, { value: options.extend[k] });
                });
            }
        }
    }
 
    return ary;
}