javascript - 如何设计链式 Model.find() 函数?

标签 javascript sql node.js orm

我正在尝试在 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)

或者可能只是一个简单的查找:

Users.find(" name = 'John' ")

要编写这个find函数,我相信我必须首先构建SQL,并在此find链的末尾执行SQL查询。

我不知道该怎么做,我能想到的就是添加一个函数,例如:doQuery(),这样当调用doQuery()函数时我就会知道是时候执行SQL查询了,例如:

Users.find(" name = 'John' ")
.orderedBy("age").desc()
.limit(0,10)
.doQuery();

我知道这是一个简单的解决方案,但我不需要额外的 doQuery() 函数。 :(

那么,我应该如何设计呢?如果您能给我一些带有注释的示例代码,那就太好了。

谢谢! (抱歉我的英语不好)

ps。我知道ORM2有一个我想要的查找功能,但我想知道如何编码它,而且我几乎无法理解 ORM2 中的代码,因为没有注释。 (我不会使用 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

我相信一定有更好的方法来实现这一目标,但这是我目前能得到的最好方法。 有意见吗?

最佳答案

如果您安排 doQuery 逻辑异步运行(但尽快),则可以实现这一点。我正在考虑这样的事情:

function User() {

    // Flag to control whether a timer was already setup
    var queryTimerSet = false;

    // This will schedule the query execution to the next tick of the
    // event loop, if it wasn't already scheduled.
    // This function is available to your model methods via closure.
    function scheduleQuery() {
        if(!queryTimerSet) {
            setTimeout(function(){
                // execute sql
                // from the query callback, set queryTimerSet back to false
            }, 0);
            queryTimerSet = true;
        }
    }

    this.find = function() {
        // ... logic that builds the sql

        scheduleQuery();
        return this;
    }

    this.orderedBy = function() {
        // ... logic that appends to the sql

        scheduleQuery();
        return this;
    }

    // etc.
}
<小时/>

一种完全不同的方法是使用单一方法来构建 SQL,并在选项对象中传递 ORDER BY 和 LIMIT 参数。那么你的调用将如下所示:

user.find({
    what : " name = 'John' ",
    orderedBy : "age DESC",
    limit : "0,10"
});

这比您想要做的更适合 SQL 查询。你所拥有的看起来像 MongoDB 之类的 noSQL 东西,其中获取记录和排序是单独的操作(我认为)。

关于javascript - 如何设计链式 Model.find() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17837922/

相关文章:

javascript - 更改按钮的字体大小

SQL AVG() 返回 3 列的错误结果

javascript - Kafka-node 连接到 kafka 的本地实例,但未连接到远程 kafka 服务器

sql - Postgres 函数

json - Firebase 更新特定字段?

node.js - request.getAsync() 只返回 1 个参数

javascript - 根据屏幕尺寸调整 Canvas 大小并将图像打印到 Canvas

javascript - 如何因超时而停止轮询?

javascript - 在 JavaScript 中的表单字段旁边打印文本

sql - 使用连接更新表,如果不存在则为 NULL