Code coverage report for src/Common/Assertion.js

Statements: 100% (28 / 28)      Branches: 100% (4 / 4)      Functions: 100% (4 / 4)      Lines: 100% (28 / 28)      Ignored: none     

All files » src/Common/ » Assertion.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    1                         1   1 1 1 1 1 1 1 1 1                 1                   1 5                       1   557 2     555                                             1   590 590       590 590   2346 586 586             590       1    
'use strict';
 
var _               = require("lodash"),
    Safe            = require("./Safe"),
    Chain           = require("./Chain"),
    ChainContext    = require("./Chain/ChainContext");
 
 
/**
 *
 * The Chainable functions
 *
 * @type {Object}
 *
 */
var ChainableFns = {};
 
ChainableFns.required   = require("./Assert/Required");
ChainableFns.string     = require("./Assert/String");
ChainableFns.object     = require("./Assert/Object");
ChainableFns.array      = require("./Assert/Array");
ChainableFns.number     = require("./Assert/Number");
ChainableFns.max        = require("./Assert/Max");
ChainableFns.min        = require("./Assert/Min");
ChainableFns.regex      = require("./Assert/Regex");
ChainableFns.instanceOf = require("./Assert/InstanceOf");
 
/**
 *
 * The Assertion functions
 *
 * @type {Object}
 *
 */
var AssertionFns = {};
 
/**
 *
 * Tests if the combination of rules are valid
 *
 * @param  {*}          result
 * @param  {Error}      err
 * @return {Boolean}
 */
AssertionFns.isValid = function(result, err){
    return !err;
};
 
/**
 *
 * Assert
 *
 * @param  {*}      result
 * @param  {Error}  err
 * @return {}
 *
 */
AssertionFns.assert = function(result, err){
 
    if(err){
        throw err;
    }
 
    return result;
 
};
 
/**
 *
 * Construct a new Assertion provider. This can have some custom actions.
 * @class
 *
 * @param {Object} fns
 *
 * @return {Object}
 *
 * @example
 *
 * Assertion({})
 *     .required()
 *     .string()
 *     .max(10)
 *     .min(5)
 *     [ .isValid("aaaa") | .assert("aaaa") ]
 *
 */
var Assertion = function(fns){
 
    fns = Safe.object(fns);
    fns = _.assign({}, fns, ChainableFns);
 
    /// Get the current ChainContext of the assertion, in order
    /// to keep the assertion state.
    var context = null;
    _.each(arguments, function(arg){
 
        if(arg instanceof ChainContext){
            context = arg;
            return false;
        }
 
    });
 
    /// Apply Cahin to the same context
    /// this is important because we can invoke "instaceof Assertion"
    Chain.apply(this, [fns, AssertionFns, { pipe: false, type: Assertion }, context]);
 
};
 
module.exports = Assertion;