【发布时间】:2013-07-24 15:05:26
【问题描述】:
我正在尝试在 Node.js 中编写 ORM。我想声明一个名为 Model 的类,它将用于声明一个数据对象,例如:
Users = new Model(someModelRules);
newUser = new Users(userInfomation);
数据模型User 有一个名为find() 的函数。现在,我想将find() 链接起来,比如:
Users.find(" name = 'John' ")
.orderedBy("age").desc()
.limit(0,10)
或者只是一个简单的find:
Users.find(" name = 'John' ")
要编码这个find函数,我相信我必须先构建SQL,并在这个find链的末尾进行SQL查询。
我不知道怎么做,我能想到的就是添加一个像:doQuery()这样的函数,这样我就会知道在调用doQuery()函数时是时候进行SQL查询了,比如:
Users.find(" name = 'John' ")
.orderedBy("age").desc()
.limit(0,10)
.doQuery();
我知道这是一个简单的解决方案,但我不想要额外的 doQuery() 函数。 :(
那么,我应该如何设计呢?如果您能给我看一些带有 cmets 的示例代码,那就太好了。
谢谢! (对不起我的英语不好)
ps。我知道ORM2 有一个我想要的查找功能,但我想知道如何对其进行编码,而且我几乎无法理解 ORM2 中的代码,因为没有 cmets。 (我不会使用 orm2。)
==================================解决方案============= =================
受@bfavaretto 启发:
function User() {
this.find = function(id, condition) {
return new findChain(id, condition);
}
}
function findChain(id, condition) {
this._id = id
this._condition = condition
this.queryTimerSet = false;
this.scheduleQuery = function () {
var self = this;
if(!self.queryTimerSet) {
console.log('[TEST CASE: ' + self._id + '] Insert query into eventLoop');
setTimeout(function(){
console.log('[TEST CASE: ' + self._id + '] Start query: '+self._condition);
}, 0);
self.queryTimerSet = true;
} else {
console.log('[TEST CASE: ' + self._id + '] No need to insert another query');
}
}
this.orderedBy = function(column) {
console.log('[TEST CASE: ' + this._id + '] orderedBy was called');
this._condition = this._condition + ' ORDER BY ' + column
this.scheduleQuery();
return this;
}
this.desc = function() {
// simply add DESC to the end of sql
this._condition = this._condition + ' DESC'
}
this.scheduleQuery();
}
var user = new User();
user.find(1,'SELECT * FROM test').orderedBy('NAME1').desc();
user.find(2,'SELECT * FROM test').orderedBy('NAME2');
user.find(3,'SELECT * FROM test');
运行这段代码,你会得到结果:
[TEST CASE: 1] Insert query into eventLoop
[TEST CASE: 1] orderedBy was called
[TEST CASE: 1] No need to insert another query
[TEST CASE: 2] Insert query into eventLoop
[TEST CASE: 2] orderedBy was called
[TEST CASE: 2] No need to insert another query
[TEST CASE: 3] Insert query into eventLoop
[TEST CASE: 1] Start query: SELECT * FROM test ORDER BY NAME1 DESC
[TEST CASE: 2] Start query: SELECT * FROM test ORDER BY NAME2
[TEST CASE: 3] Start query: SELECT * FROM test
我相信一定有更好的方法来实现这一点,但这是我目前能得到的最好的方法。 有cmets吗?
【问题讨论】:
标签: javascript sql node.js orm