All files / roosterjs-content-model-dom/lib/modelApi/metadata validate.ts

100% Statements 22/22
100% Branches 38/38
100% Functions 4/4
100% Lines 22/22

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 661x                   1x 4455x 4455x 2139x 2316x       61x   2255x   352x     352x     687x         687x     466x     466x     30x       31x 30x     720x     2753x   720x       4394x       6x    
import { getObjectKeys } from '../../domUtils/getObjectKeys';
import type { Definition } from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Validate the given object with a type definition object
 * @param input The object to validate
 * @param def The type definition object used for validation
 * @returns True if the object passed the validation, otherwise false
 */
export function validate<T>(input: any, def: Definition<T>): input is T {
    let result = false;
    if ((def.isOptional && typeof input === 'undefined') || (def.allowNull && input === null)) {
        result = true;
    } else if (
        (!def.isOptional && typeof input === 'undefined') ||
        (!def.allowNull && input === null)
    ) {
        return false;
    } else {
        switch (def.type) {
            case 'string':
                result =
                    typeof input === 'string' &&
                    (typeof def.value === 'undefined' || input === def.value);
                break;
 
            case 'number':
                result =
                    typeof input === 'number' &&
                    (typeof def.value === 'undefined' || areSameNumbers(def.value, input)) &&
                    (typeof def.minValue === 'undefined' || input >= def.minValue) &&
                    (typeof def.maxValue === 'undefined' || input <= def.maxValue);
                break;
 
            case 'boolean':
                result =
                    typeof input === 'boolean' &&
                    (typeof def.value === 'undefined' || input === def.value);
                break;
 
            case 'array':
                result =
                    Array.isArray(input) &&
                    (typeof def.minLength === 'undefined' || input.length >= def.minLength) &&
                    (typeof def.maxLength === 'undefined' || input.length <= def.maxLength) &&
                    input.every(x => validate(x, def.itemDef));
                break;
 
            case 'object':
                result =
                    typeof input === 'object' &&
                    getObjectKeys(def.propertyDef).every(x =>
                        validate(input[x], def.propertyDef[x])
                    );
                break;
        }
    }
 
    return result;
}
 
function areSameNumbers(n1: number, n2: number) {
    return Math.abs(n1 - n2) < 1e-3;
}