w3ctech

thinkjs实现类似thinkphp的模型类自动完成和自动验证

既然框架原来没有这个功能,我们又不能修改框架内的Model.js,那就只能用继承来扩展: 首先CommonModel.js:

 *
 * @author     richen
 * @copyright  Copyright (c) 2014- <ric3000(at)163.com>
 * @license    CC BY-NC-ND
 * @version    14-8-29
 */
module.exports = Model(function(){
    "use strict";
    return {
        _validate:[],
        _auto:[],
        /**
         * 自动验证
         * @param data
         * @param type
         * @returns {*}
         * @private
         */
        _autoValidation: function(data,type){
            var self = this;
            //解析_validate规则
            //验证字段,验证规则[,附加规则],错误提示[,验证时间 1新增 2编辑 null新增和编辑]
            /*this._validate = [
             {name: "email", valid: "email", msg: "email不合法",type: 1},
             {name: "pwd", valid: ["length"], length_args: [6, 20], msg:"密码长度不合法" ,type: 2},
             {name: "url", valid: "required", msg: "url必填"},
             {name: "username", valid: "function",func_name:"checkName", msg: "username不合法"}
             ];*/
            try{
                if(!isEmpty(this._validate)){
                    var Valid = thinkRequire('Valid');
                    var promises = this._validate.map(function(validate){
                        if(isEmpty(validate.name)){
                            return getPromise(true);
                        }else{
                            validate.type = validate.type || type;
                            if(validate.valid == 'function'){
                                if(validate.type === type){
                                    if(self[validate.func_name](data) === false){
                                        return getPromise(getObject(validate.name,validate.msg));
                                    }else{
                                        return getPromise(true);
                                    }
                                }else{
                                    return getPromise(true);
                                }
                            }else{
                                //此处修改为字段存在才验证
                                //if(isEmpty(data[validate.name]) && validate.valid !== 'required'){
                                if(data.hasOwnProperty(validate.name)){
                                    if(validate.type === type){
                                        //删除type属性兼容Vaild类
                                        delete validate.type;
                                        validate.value = data[validate.name];

                                        return getPromise(Valid(validate));
                                    }else{
                                        return getPromise(true);
                                    }
                                }else{
                                    return getPromise(true);
                                }
                            }
                        }

                    });

                    return Promise.all(promises).then(function (status) {
                        for(var name in status){
                            if(!isEmpty(status[name]) && status[name] !== true){
                                return Object.values(status[name]);
                            }
                        }
                        return true;
                    });
                }else{
                    return getPromise(true);
                }
            }catch (e){return getPromise({"errmsg":e});}

        },
        /**
         * 自动完成
         * @param data
         * @param type
         * @private
         */
        _autoOperation: function(data, type){
            var self = this;
            //解析完成规则
            //字段,自动填写的值[,完成时间 1新增 2编辑 null新增和编辑]
            /*this._auto = [
             {name: "email", value: "xxx@xxx.cn", type: 1},
             {name: "username", value: "admin", type: 2},
             {name: "url", value: 'http://xxx.com'},
             {name: "username", value: "function",func_name:"autoName"}
             ];*/
            try{
                if(!isEmpty(this._auto)){
                    var auto;
                    for(var i in this._auto){
                        auto = this._auto[i];
                        if(isEmpty(auto.name)){
                            continue;
                        }
                        auto.type = auto.type || type;
                        if(auto.type !== type){
                            continue;
                        }
                        if(auto.value === 'function' && auto.func_name !== undefined){
                            func_value = self[auto.func_name](data);
                            //自定义方法内没有定义返回结果,data内不增加此属性
                            if(func_value !== undefined){
                                data[auto.name] = func_value;
                            }
                        }else{
                            data[auto.name] = auto.value;
                        }
                    }
                }
                return getPromise(data);
            }catch (e){return getPromise({"errmsg":e});}
        },

        add: function(data, options, replace){
            var self = this;
            return Promise.all([this._autoValidation(data,1),this._autoOperation(data,1)]).then(function (result) {
                if(result[0] !== true){
                    return getPromise({"errmsg":result[0]});
                }
                return self.super_("add", [result[1], options, replace]);
            });
        },
        update: function (data, options) {
            var self = this;
            return Promise.all([this._autoValidation(data,2),this._autoOperation(data,2)]).then(function (result) {
                if(result[0] !== true){
                    return getPromise({"errmsg":result[0]});
                }
                return self.super_("update", [result[1], options]);
            });
        }
    }
});

在具体业务模型类例如 UserModel 去继承CommonModel,代码:

 *
 * @author     richen
 * @copyright  Copyright (c) 2014- <ric3000(at)163.com>
 * @license    CC BY-NC-ND
 * @version    14/10/31
 */
module.exports = Model('Common/CommonModel',function(){
    "use strict";
    return {
        tableName: 'User',
        //验证字段,验证规则[,附加规则],错误提示[,验证时间(1新增 2编辑 null新增和编辑)]
        _validate : [
            {name: "nickname", valid: 'required', msg: "姓名必填"},
            {name: "email", valid: "email", msg: "email不合法"},
            {name: "password", valid: ["length"], length_args: [6, 20], msg:"密码长度不合法" ,type: 2},
            {name: "username", valid: "function",func_name:"checkName", msg: "username不合法"}
        ],
        //字段,自动填写的值[,完成时间(1新增 2编辑 null新增和编辑)]
        _auto:[
            {name: "update_time", value: php.time()},
            {name: "username", value: "function",func_name:"autoName"}
        ],

        checkName: function (data) {
            return true;
        },

        autoName: function(data){
            return "aaa";
        }
}
});

规则兼容 Thinkjs框架本身的验证写法,且增强支持函数类型验证: 自动验证规则写法:

//验证字段,验证规则[,附加规则],错误提示[,验证时间(1新增 2编辑 null新增和编辑)]
        _validate : [
            {name: "nickname", valid: 'required', msg: "姓名必填"},
            {name: "email", valid: "email", msg: "email不合法"},
            {name: "password", valid: ["length"], length_args: [6, 20], msg:"密码长度不合法" ,type: 2},
            {name: "username", valid: "function",func_name:"checkName", msg: "username不合法"}
        ]

自动完成规则写法:

//字段,自动填写的值[,完成时间(1新增 2编辑 null新增和编辑)]
        _auto:[
            {name: "update_time", value: php.time()},
            {name: "username", value: "function",func_name:"autoName"}
        ]

在控制器调用Model执行 add 和 update 方法的时候,就会自动执行 完成和验证

w3ctech微信

扫码关注w3ctech微信公众号

共收到0条回复