
說起ORM,Object Relational Mapping,有Hibernate,JPA等成熟的Java框架。 Sequelize是JS端的hibernate,可以和十分著名的Express js server一起使用,完成server端到數(shù)據(jù)庫的CRUD等等操作。
Promise based, Sequelize和Hibernate最大的區(qū)別在于,它的調(diào)用基于bluebird的異步調(diào)用引擎,我們知道,在Javascript的世界里,很多調(diào)用是通過Callback函數(shù)來完成的而并非是順序執(zhí)行的,使用Sequelize,我們也要注意這一點(diǎn)。
從模型說起
Promise要把Javascript Object轉(zhuǎn)換成數(shù)據(jù)庫的一行,首先,它需要知道數(shù)據(jù)庫表結(jié)構(gòu),當(dāng)然,Sequelize主要是支持Postgres, Mysql之類的關(guān)系型數(shù)據(jù)庫。
npm install -g sequelize-auto
sequelize-auto -h 127.0.0.1 -d ocsp -u root -x 123 -p 3306 ---dialect mysql -o "./server/models/"
sequelize-auto是一個幫助我們快速生成表結(jié)構(gòu)的工具,上面給出了一個通過連接mysql生成數(shù)據(jù)庫表結(jié)構(gòu)代碼的例子。
/* jshint indent: 2 */
"use strict";
module.exports = function(sequelize, DataTypes) {
return sequelize.define('STREAM_EVENT', {
id: {
type: DataTypes.INTEGER(16),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
}, {
createdAt: false,
updatedAt: false,
tableName: 'STREAM_EVENT'
});
};
首先生成的代碼沒有使用"use strict";,如果是需要運(yùn)行在嚴(yán)格模式下,需要自己添加。其次,createdAt和updateAt要寫成false,默認(rèn)true需要數(shù)據(jù)庫表里面有這兩個字段。
錯誤處理
Javascript Promise的錯誤處理有讓人迷糊的地方。
p.then(onFulfilled, onRejected);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
p.catch(onRejected);
p.catch(function(reason) {
// 拒絕
});
首先是ES6里面Promise的then提供兩個參數(shù),分別是success和error的兩個callback函數(shù),另外,Promise提供catch方法,用來處理error的情況,所以從某種角度上說,第二個callback函數(shù)的作用和catch是一樣的。
Tips: 在這里,我們推薦使用catch函數(shù),因?yàn)閏atch返回的還是一個Promise,這對于Promise chain的調(diào)用很有好處,例如官方給出了以下例子??梢钥闯?,catch后面還有then。
Warning:在最新版本的Angular里面,已經(jīng)徹底刪除了Promise的success和error方法,因?yàn)閷romise chain的傳遞有影響,一般then(function(item){})這里面的item,要再次解析,例如包裝在item.data里面,而在success中則直接是data的值,這對于Promise chain有混淆,所以success被廢棄了,這里不推薦使用。
var p1 = new Promise(function(resolve, reject) {
resolve('Success');
});
p1.then(function(value) {
console.log(value); // "成功!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
// 以下行為與上述相同
p1.then(function(value) {
console.log(value); // "成功!"
return Promise.reject('oh, no!');
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
使用事務(wù)
sequelize的事務(wù)處理非常強(qiáng)大。以下給出一個transaction使用的例子,注意在transaction里面使用的return函數(shù)來返回promise的方式,用來保證sequelize執(zhí)行同步。
sequelize.transaction(function(t) {
return EventDef.find({where: {id: req.params.id}, transaction: t}).then(function (event) {
let result = event.dataValues;
if(result.status === status){
return sequelize.Promise.reject();
}
if(result.owner !== username){
return sequelize.Promise.reject();
}
result.status = status;
return EventDef.update(result, {where: {id: req.params.id}, transaction: t});
});
}).then(function(){
res.send({success: true});
}).catch(function (e) {
console.log(e);
res.status(500).send(trans.databaseError);
});
使用關(guān)聯(lián)關(guān)系
Sequelize中使用include hook可以方便的進(jìn)行表關(guān)聯(lián)。
let EventDef = require('../model/STREAM_EVENT')(sequelize, Sequelize);
let CEP = require('../model/STREAM_EVENT_CEP')(sequelize, Sequelize);
EventDef.hasOne(CEP, {foreignKey:'event_id', targetKey:'id'});
EventDef.find({
where:{
id: req.params.id
},
include: {
model: CEP
}
}).then(function(event){
res.send(event);
}, function(){
res.status(500).send(trans.databaseError);
});
Warning: 一般我們使用sequelize都是在express router里面,注意的是在一個router里面,只能有一個response,由于sequelize是異步的,注意是否進(jìn)行了多次返回。
router.put('/:id', function(req, res){
let event = req.body.event;
EventDef.find({attributes: ["owner"], where: {id: event.id}}).then((owner)=> {
res.send({success: true});
});
//res.send(),這里不能出現(xiàn),注意
小結(jié)
Sequelize是一個非常優(yōu)秀的ORM工具,了解Promise的運(yùn)行機(jī)制,注意它的異步性,就能利用好它做數(shù)據(jù)庫操作了。