node.js学习笔记(28) node-orm进阶三

也许你想监听Model实例的创建、修改、获取或者删除,那么正好node-rom为Model定义了一系列事件。

  • afterLoad : (no parameters) Right after loading and preparing an instance to be used;
  • afterAutoFetch : (no parameters) Right after auto-fetching associations (if any), it will trigger regardless of having associations or not;
  • beforeSave : (no parameters) Right before trying to save;
  • afterSave : (bool success) Right after saving;
  • beforeCreate : (no parameters) Right before trying to save a new instance (prior to beforeSave);
  • afterCreate : (bool success) Right after saving a new instance;
  • beforeRemove : (no parameters) Right before trying to remove an instance;
  • afterRemove : (bool success) Right after removing an instance;
  • beforeValidation : (no parameters) Before all validations and prior to beforeCreate and beforeSave;

Node-orm将这些events定义为hook,钩子。

钩子实际上是一个处理消息的程序段,通过系统调用,把它挂入系统。每当特定的消息发出,在没有到达目的窗口前,钩子程序就先捕获该消息,亦即钩子函数先得到控制权。这时钩子函数即可以加工处理(改变)该消息,也可以不作处理而继续传递该消息,还可以强制结束消息的传递。

这些事件刚好可以为对model实例增删改查的前后进行拦截,然后对model实例做一些加工处理。因此,钩子这个名字正合适。


这些事件都可以通过this来调用model实例本身。

var Person = db.define("person", {
    name    : String,
    surname : String
}, {
    hooks: {
        beforeCreate: function (next) {
            console.log(this.name);
            next();
        }
    }
});

一共9个事件,不是before*就是after*。但从一组来看,先后顺序很好区分,比如beforeCreate和afterCreate,分别是在insert的一前一后。

但是insert并不是仅仅关联beforeCreate和afterCreate这么简单,它还关联afterLoad、beforeVlidation、beforeSave和afterSave,那么谁先谁后呢?

通过程序来区分吧。


hook-insert.js:

var orm = require("orm");

orm.connect('mysql://root:root@localhost:3306/nodejs', function(err, db){
    if (err) throw err;
    var User = db.define("user", {
        id          :{type:'serial', mapsTo:'id', unique:true, size:11},
        name        :{type:'text', mapsTo:'name'},
        username    :{type:'text', mapsTo:'username'},
        password    :{type:'text', mapsTo:'password'},
        birthday    :{type:'date', mapsTo:'birthday', time:true}
    },{
        validations:{
            username:orm.enforce.unique('The username is already existed.')
        },
        hooks:{
            afterLoad : function(next){
                console.log('This is afterLoad');
                next();
            },
            afterAutoFetch : function(next){
                console.log('This is afterAutoFetch')
                next();
            },
            beforeSave:function(next){
                console.log('This is beforeSave')
                next();
            },
            afterSave:function(success){
                console.log('This is afterSave')
            },
            beforeCreate :function(next){
                console.log('This is beforeCreate')
                next();
            },
            afterCreate :function(success){
                console.log('This is afterCreate')
            },
            beforeRemove :function(next){
                console.log('This is beforeRemove')
                next();
            },
            afterRemove :function(success){
                console.log('This is afterRemove')
            },
            beforeValidation :function(next){
                console.log('This is beforeValidation')
                next();
            }
        }
    });

    var user = new User(
        {
            name:'e',
            username:'ee',
            password:'eee',
            birthday:'2010-10-10 10:10:10'
        }
    );
    user.save(function(err){
        if(err){
            console.log(err);
        }
    });

});

运行hook-insert:

node hook-insert.js
This is afterLoad
This is afterAutoFetch
This is beforeValidation
This is beforeCreate
This is beforeSave
This is afterCreate
This is afterSave

hook-load.js:
var orm = require("orm");

orm.connect('mysql://root:root@localhost:3306/nodejs', function(err, db){
    if (err) throw err;
    var User = db.define("user", {
        id          :{type:'serial', mapsTo:'id', unique:true, size:11},
        name        :{type:'text', mapsTo:'name'},
        username    :{type:'text', mapsTo:'username'},
        password    :{type:'text', mapsTo:'password'},
        birthday    :{type:'date', mapsTo:'birthday', time:true}
    },{
        validations:{
            username:orm.enforce.unique('The username is already existed.')
        },
        hooks:{
            afterLoad : function(next){
                console.log('This is afterLoad');
                next();
            },
            afterAutoFetch : function(next){
                console.log('This is afterAutoFetch')
                next();
            },
            beforeSave:function(next){
                console.log('This is beforeSave')
                next();
            },
            afterSave:function(success){
                console.log('This is afterSave')
            },
            beforeCreate :function(next){
                console.log('This is beforeCreate')
                next();
            },
            afterCreate :function(success){
                console.log('This is afterCreate')
            },
            beforeRemove :function(next){
                console.log('This is beforeRemove')
                next();
            },
            afterRemove :function(success){
                console.log('This is afterRemove')
            },
            beforeValidation :function(next){
                console.log('This is beforeValidation')
                next();
            }
        }
    });

    User.find({username:'ee'}, function(err, items) {
        for(var i=0;i<items.length;i++){
            console.log(JSON.stringify(items[i]));
        }
    });

});


运行hook-load.js:

node hook-load.js
This is afterLoad
This is afterAutoFetch
{"id":8,"name":"e","username":"ee","password":"eee","birthday":"2010-10-10T02:10:10.000Z"}



hook-update.js:

var orm = require("orm");

orm.connect('mysql://root:root@localhost:3306/nodejs', function(err, db){
    if (err) throw err;
    var User = db.define("user", {
        id          :{type:'serial', mapsTo:'id', unique:true, size:11},
        name        :{type:'text', mapsTo:'name'},
        username    :{type:'text', mapsTo:'username'},
        password    :{type:'text', mapsTo:'password'},
        birthday    :{type:'date', mapsTo:'birthday', time:true}
    },{
        validations:{
            username:orm.enforce.unique('The username is already existed.')
        },
        hooks:{
            afterLoad : function(next){
                console.log('This is afterLoad');
                next();
            },
            afterAutoFetch : function(next){
                console.log('This is afterAutoFetch')
                next();
            },
            beforeSave:function(next){
                console.log('This is beforeSave')
                next();
            },
            afterSave:function(success){
                console.log('This is afterSave')
            },
            beforeCreate :function(next){
                console.log('This is beforeCreate')
                next();
            },
            afterCreate :function(success){
                console.log('This is afterCreate')
            },
            beforeRemove :function(next){
                console.log('This is beforeRemove')
                next();
            },
            afterRemove :function(success){
                console.log('This is afterRemove')
            },
            beforeValidation :function(next){
                console.log('This is beforeValidation')
                next();
            }
        }
    });

    User.find({username:'ee'}, function(err, items) {
        for(var i=0;i<items.length;i++){
            items[i].username = 'ff';
            items[i].save();
        }
    });

});


运行hook-update.js:

node hook-update.js
This is afterLoad
This is afterAutoFetch
This is beforeValidation
This is beforeSave
This is afterSave

hook-delete.js:
var orm = require("orm");

orm.connect('mysql://root:root@localhost:3306/nodejs', function(err, db){
    if (err) throw err;
    var User = db.define("user", {
        id          :{type:'serial', mapsTo:'id', unique:true, size:11},
        name        :{type:'text', mapsTo:'name'},
        username    :{type:'text', mapsTo:'username'},
        password    :{type:'text', mapsTo:'password'},
        birthday    :{type:'date', mapsTo:'birthday', time:true}
    },{
        validations:{
            username:orm.enforce.unique('The username is already existed.')
        },
        hooks:{
            afterLoad : function(next){
                console.log('This is afterLoad');
                next();
            },
            afterAutoFetch : function(next){
                console.log('This is afterAutoFetch')
                next();
            },
            beforeSave:function(next){
                console.log('This is beforeSave')
                next();
            },
            afterSave:function(success){
                console.log('This is afterSave')
            },
            beforeCreate :function(next){
                console.log('This is beforeCreate')
                next();
            },
            afterCreate :function(success){
                console.log('This is afterCreate')
            },
            beforeRemove :function(next){
                console.log('This is beforeRemove')
                next();
            },
            afterRemove :function(success){
                console.log('This is afterRemove')
            },
            beforeValidation :function(next){
                console.log('This is beforeValidation')
                next();
            }
        }
    });

    User.find({username:'ff'}, function(err, items) {
        for(var i=0;i<items.length;i++){
            items[i].remove();
        }
    });

});


运行hook-delete.js:

node hook-delete.js
This is afterLoad
This is afterAutoFetch
This is beforeRemove
This is afterRemove

从上面增、删、改、查四个程序的运行结果不难看出:

跟insert有关的事件有7个,按顺序分别是afterLoad、afterAutoFetch、beforeValidation、beforeCreate、beforeSave、afterCreate、afterSave。

跟udpate有关的事件有5个,按顺序分别是afterLoad、afterAutoFetch、beforeValidation、beforeSave、afterSave。

跟selete有关的事件有2个,按顺序分别是afterLoad、afterAutoFetch。

跟delete有关的事件有2个,按顺序分别是beforeRemove、afterRemove。

另外,除了afterSave、afterCreate和afterRemove,其他事件都有next参数,next是一个回调函数用于执行下一步,如果没next,程序将就此终止。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值