Code coverage report for src/Common/Schema/Mixins/SchemaExecutionHelper.js

Statements: 100% (77 / 77)      Branches: 98.39% (61 / 62)      Functions: 100% (9 / 9)      Lines: 100% (77 / 77)      Ignored: none     

All files » src/Common/Schema/Mixins/ » SchemaExecutionHelper.js
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    1                                             1   50 50     50       50 1       49       48 1         50 2     48                                 1   21     21       21       28       28 24       4 4         14 4       10         28 30         21                                     1   23     23       23 3       23   12       12 10         2     12 5             23 8       15   47 18     47       15                         1                                   158     158     158       158 155         158 9     149       137 10         158   146       31   31     31 31   12 12               158 29     129                                         50       50     48 21     27 23     4           1  
"use strict";
 
var _                   = require("lodash"),
    Safe                = require("../../Safe"),
    Type                = require("../../Type"),
    Assert              = require("../../Assert"),
    ExceptionList       = require("../../Exception/ExceptionList"),
    Exception           = require("../../Exception/Exception"),
    Types               = require("../Types");
    
 
/**
 *
 * Prepares and validates the SchemaDefinition for the given 
 * value.
 *
 * @throw {ExceptionList}
 *
 * @param  {SchemaDefinition} schema
 * @param  {*}      value
 * @param  {Object} validationFns
 *
 * @return {SchemaDefinition}
 *
 */
var prepareSchema = function(schema, value, validationFns){
 
    value           = Safe.value(value);
    validationFns   = Safe.object(validationFns);
 
    /* jshint -W064 */
    var errors = new ExceptionList();
 
    /// If not defined and its required throw
    /* jshint -W041 */
    if(schema.required && value == null){
        errors.push(
            new Exception("VALIDATION_REQUIRED"));
    }
    /* jshint -W041 */
    else if(!schema.required && value == null){
        /// continue (optional parameter)
    }
    /// check for compatibility of types if any flag is not used
    else if(!schema.any && Type.of(schema.schema) !== Type.of(value)){
        errors.push(
            new Exception("VALIDATION_TYPE", { expected: Type.of(schema.schema), value: Type.of(value) }));
    }
 
    /// if there's error throw them
    if(errors.length){
        throw errors;
    }
 
    return schema;
 
};
 
/**
 *
 * Prepares and validates the SchemaDefinition for the given 
 * object.
 *
 * @throws {ExceptionList} If a validation function occurs
 * 
 * @param  {SchemaDefinition} schema
 * @param  {Object} value
 *
 * @return {SchemaDefinition}
 *
 */
var prepareObject = function(schema, value){
 
    value = Safe.object(value);
 
    /* jshint -W064 */
    var errors      = new ExceptionList(),
        result      = {},
        valueKeys   = _.keys(value);
 
    _.each(
        schema.schema,
        function(schemaValue, key){
 
            var isRegExp = Type.isRegExpStr(key),
                keys     = [];
 
            /// key is not a regexp string
            if(!isRegExp){
                keys = [ key ];
            }
            else {
                /// key is a regexp string
                var regexp  = Safe.regexp(key);
                keys = _.filter(
                    valueKeys,
                    function(key){
 
                        /// if there's a definition of the schema don't include it
                        if(schema.schema[key] !== undefined){
                            return false;
                        }
 
                        /// test if the regex match
                        return !!regexp.exec(key);
 
                    });
            }
 
            _.each(keys, function(val) {
                result[val] = schemaValue;
            });
 
        });
 
    return schema.clone({
        schema: result
    });
 
};
 
/**
 *
 * Prepares and validates the SchemaDefinition for the given 
 * array.
 *
 * @throws {ExceptionList} If a validation error occurs
 *
 * @param  {SchemaDefinition} schema
 * @param  {Array} value
 *
 * @return {SchemaDefinition}
 *
 */
var prepareArray = function(schema, value){
 
    value = Safe.array(value);
 
    /* jshint -W064 */
    var errors  = new ExceptionList(),
        result  = [],
        index   = 0;
 
    if( !schema.repeatable && schema.schema.length != value.length ){
        errors.push(
            new Exception("VALIDATION_INVALID_LIST_LENGTH", { value: value.length, expected: schema.schema.length }));
    }
 
    if(schema.repeatable){
 
        var isRepeatable = true;
 
        /// if the value contains elements check if its divisible by 
        /// the repeat count
        if(value.length > 0 && value.length != schema.schema.length){
            isRepeatable = value.length % schema.schema.length === 0;
        }
        /// otherwise is only repeatable if the array contains no 
        /// element
        else {
            isRepeatable = (value.length === schema.schema.length) && (value.length === 0);
        }
 
        if(!isRepeatable){
            errors.push(
                new Exception("VALIDATION_INVALID_LIST_LENGTH_MULTIPLE_OF", { value: value.length, expected: schema.schema.length }));    
        }
        
    }
 
    /// if errors exist throw them
    if(errors.length){
        throw errors;
    }
 
    /// create the result array
    for(var i=0; i<value.length; i++){
 
        if(schema.repeatable && index >= schema.schema.length){
            index = 0;
        }
 
        result.push(schema.schema[index++]);
 
    }
 
    return schema.clone({
        schema: result
    });
 
};
 
/**
 *
 * Schema Conversion conversion methods
 * 
 * @type {Object}
 * 
 */
var SchemaExecutionHelper = {
 
    /**
     *
     * Get the value according to the given schema, by applying 
     * default values, coercing values, ...
     *
     * @throws {ExceptionList} If the validation fails
     * 
     * @param  {SchemaDefinition} schema
     * @param  {*} value
     *
     * @return {*}
     *
     */
    prepareValue: function(schema, value, validationFns){
 
        /// validate and normalize arguments
        Assert.instanceOf(Types.SchemaDefinition)
            .assert(schema);
 
        value = Safe.value(value);
 
        /// initalize the list of errors
        var errors = new ExceptionList();
 
        /// if not strict tries to normalize
        /// the value (e.g. a number can be on string representation )
        if(!schema.strict){
            value = Safe.coerce(value, schema.schema);
        }
 
        /// if the value is required and it has no value, throw error
        /* jshint -W041 */
        if(schema.required && value == null){
            errors.push(
                new Exception("VALIDATION_REQUIRED"));
        }
        else if(!schema.required && value == null){
            /// ignore, and not fallback on the other else's
        }
        /// if a value exists find out if types are compatible
        else if(!schema.any && Type.of(schema.schema) !== Type.of(value)){
            errors.push(
                new Exception("VALIDATION_TYPE", { expected: Type.of(schema.schema), value: Type.of(value) }));
        }
 
        /// always run if value is required or value is specified.
        if(schema.required || value !=null){
 
            _.each(
                schema.validations,
                function(v){
 
                    v = Safe.object(v);
 
                    var fn      = Safe.function(validationFns[v.name]),
                        args    = Safe.array(v.args);
 
                    try{
                        fn.apply({}, [value].concat(args));
                    }catch(e){
                        var error = new Exception(e.message);
                        errors.push(error);
                    }
 
            });
 
        }
 
        /// check if any error was detected
        if(errors.length){
            throw errors;
        }
 
        return value;
 
    },
 
    /**
     *
     * Gets the schema for the given value. If the schema is an object it 
     * will expand its keys regular expressions. If the schema is an array 
     * it will apply its properties to the given value.
     *
     * @throws {ExceptionList} If a validation error occurs
     *
     * @param  {SchemaDefinition} schema
     * @param  {*}      value
     * @param  {Object} validationFns
     * 
     * @return {SchemaDefinition}
     * 
     */
    prepareSchema: function(schema, value, validationFns){
 
        Assert.instanceOf(Types.SchemaDefinition)
            .assert(schema);
 
        /// prepare the schema
        schema = prepareSchema(schema, value, validationFns);
 
        /// prepare the object
        if(schema.isObject()){
            return prepareObject(schema, value);
        }
        /// prepare the array
        else if(schema.isArray()){
            return prepareArray(schema, value);
        }
 
        return schema;
 
    }
 
};
 
module.exports = SchemaExecutionHelper;