All files / mobx-decorated-models/lib setup-model.js

100% Statements 31/31
96.77% Branches 30/31
100% Functions 7/7
100% Lines 27/27

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      76x       220x   21x                 21x       27x 27x       76x 64x     206x             131x 118x 118x   118x 110x 30x 30x   30x 30x 28x         110x 41x 41x 34x         118x     118x 42x     118x    
import { markNonserializable } from './serializable';
 
function hasInterceptors(model) {
    return Boolean(model.constructor.$mxdm && model.constructor.$mxdm.interceptors.length);
}
 
export function getSchema(klass) {
    if (klass.$mxdm) { return klass.$mxdm; }
 
    Object.defineProperty(klass, '$mxdm', {
        enumerable: false,
        writable: false,
        configurable: true,
        value: Object.freeze({
            interceptors: [],
            properties: new Map(),
        }),
    });
    return klass.$mxdm;
}
 
export function addLazyInitializer(target, fn) {
    const { interceptors } = getSchema(target.constructor);
    interceptors.push(fn);
}
 
export function attachInterceptors(model) {
    if (!hasInterceptors(model) || model.$mxdbDidAttachInterceptors) { return; }
    Object.defineProperty(model, '$mxdbDidAttachInterceptors', {
        enumerable: false, writable: false, configurable: true, value: true,
    });
    getSchema(model.constructor).interceptors.forEach(fn => fn(model));
}
 
export function setupModel({
    attrs, modelClass: Klass, array, defaultAttributes,
    inverseOf, parentModel, parentModelProp,
}) {
    if (!attrs) { return attrs; }
    const isObject = ('object' === typeof attrs);
    const canWrite = Object.isExtensible(attrs);
 
    if (isObject && canWrite) {
        if (defaultAttributes) {
            Eif ('function' === typeof defaultAttributes) {
                defaultAttributes = defaultAttributes.call(parentModel, array, parentModel);
            }
            Object.keys(defaultAttributes).forEach((key) => {
                if (!attrs[key]) {
                    attrs[key] = defaultAttributes[key];
                }
            });
        }
 
        if (inverseOf) {
            attrs[inverseOf] = parentModel;
            if (parentModelProp) {
                attrs[`${inverseOf}_association_name`] = parentModelProp;
            }
        }
    }
 
    const model = (Klass && 'function' === typeof Klass && !(attrs instanceof Klass)) ?
        new Klass(attrs) : attrs;
 
    if (inverseOf) {
        markNonserializable(model, inverseOf);
    }
 
    return model;
}