all files / src/ rules.ts

100% Statements 21/21
100% Branches 4/4
100% Functions 5/5
100% Lines 20/20
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                                               13× 13×     15×   15×   15×       15×   15×              
import {originRulesAnalyse, RealRules} from "./origin-rules-analyse";
import {ValidatorCollection, Validator} from "./build-in-validators";
 
interface RuleResult{
    valid: boolean
}
 
interface RuleFunction extends Function{
    (data: Object): RuleResult,
    register?: (methodName: string, fn: Function) => void
}
 
interface OriginConfig {
    [propName: string]: string
}
 
export {RuleResult, RuleFunction};
 
export function rules(config: OriginConfig): RuleFunction {
    let realRules = originRulesAnalyse(config),
        newValidators = ValidatorCollection.create(),
        ruleFn = getRuleFunction(realRules, newValidators);
 
    ruleFn.register = (methodName: string, fn: Function) => {
        newValidators[methodName] = fn;
    };
 
    return ruleFn;
}
 
function getRuleFunction(realRules: RealRules, newValidators: Validator): RuleFunction {
    return (data) => {
        for (let fieldName in realRules) {
            let filedItem = realRules[fieldName],
                dataItem = data[fieldName];
 
            for (let ruleItem of filedItem) {
 
                let params: any[];
 
                if(ruleItem.params){
                    params =  ruleItem.params.map((param) => {
                        return param.value;
                    });
                }
 
                let valid = newValidators[ruleItem.method].apply(null, [dataItem].concat(params));
 
                if (!valid) {
                    return {valid: false};
                }
            }
        }
 
        return {valid: true};
    }
}