【问题标题】:Using Koa with bluebird and pg将 Koa 与 bluebird 和 pg 一起使用
【发布时间】:2016-05-04 22:00:12
【问题描述】:

我有一个关于将 Koa 与 Postgres 结合使用的最佳方式的问题。我也(真的)喜欢使用 Bluebird,所以我采用了这种方法。

'use strict'; 

var db = require('./modules/db.js');
var koa = require('koa');
var app = koa();

app.use(function *(){

    yield db.withConnection(function *(client){

        let id = this.request.query.id;
        let simple_data = yield client.queryAsync('select name from table1 where id = $1', [id]);

        this.response.body = simple_data;
    }.bind(this));
});

app.listen(3000);

这是 db.js 文件,基本上它使用了 Bluebird 文档中提到的东西。

... bla bla, some imports

Promise.promisifyAll(pg);

function getSqlConnection() {
    var close;
    return pg.connectAsync(connectionString).spread(function(client, done) {
        close = done;
        return client;
    }).disposer(function() {
        if (close) close();
    });
}


function* withConnection(func){
    yield Promise.using(getSqlConnection(), function (client){
            return Promise.coroutine(func)(client); 
    });
}

module.exports.withConnection = withConnection;

您有什么改进的建议吗?我现在真的很喜欢它,我已经对它进行了广泛的测试(在负载下,产生错误/异常等),它似乎工作正常。我对这些生成器和其他 ES6 东西很陌生,所以我可能遗漏了一些东西。 我的问题基本上是为什么很少有人使用这种方法(我发现很难在网上找到例子)?

除了 pg 和 bluebird 之外,我也可以使用其他库,但我喜欢这些库,因为它们的下载量很大,我更喜欢使用流行的东西,因为我发现更容易找到博客文章、帮助和文档.谢谢!

【问题讨论】:

  • 在我的 Koa 应用程序中,我使用 co-pg 包装了 pg 模块以公开承诺接口,因此 co-pg 的源代码可能会让您走上正轨。我有一个基本的 Koa 1.x 应用程序,它展示了我喜欢如何将 Koa 与 Postgres 一起使用:github.com/danneu/koa-skeleton/blob/master/src/db/index.js(另请查看我的 db/util.js 文件)。

标签: javascript node.js postgresql bluebird koa


【解决方案1】:

Bluebird 是一个 Promise 库,在这方面非常出色,但不应将其用作如何或使用什么数据库库的指导。与现有的所有承诺解决方案(knex、mass.js、pg-promise 等)相比,所有Promise.promisifyAll(pg); 的东西实际上都很差。

如果您想要pg + bluebird 的最佳组合,请尝试pg-promise

var promise = require('bluebird');

var options = {
    promiseLib: promise // Use Bluebird as the promise library
};

var pgp = require("pg-promise")(options);

var db = pgp('postgres://username:password@host:port/database');

db.query('select name from table1 where id = $1', [1])
    .then(function (data) {
    })
    .catch(function (error) {
    });

该库还支持 ES6 生成器,因此您可以像示例中一样编写代码。

来自Tasks 示例:

db.task(function * (t) {
        let user = yield t.one("select * from users where id=$1", 123);
        return yield t.any("select * from events where login=$1", user.name);
    })
    .then(function (events) {
        // success;
    })
    .catch(function (error) {
        // error;
    });

【讨论】:

    【解决方案2】:

    你也可以试试 pg-native。

    来自 pg 模块文档:

    "node-postgres 包含纯 JavaScript 协议实现 这是相当快的,但您可以选择使用本机绑定 解析速度提高 20-30%。两个版本都足够 生产工作负载。要使用本机绑定,首先安装 pg 原生的。安装 pg-native 后,只需替换 require('pg') 使用 require('pg').native。"

    https://github.com/brianc/node-postgres

    【讨论】:

      猜你喜欢
      • 2015-12-03
      • 1970-01-01
      • 2023-03-16
      • 2015-09-11
      • 2017-01-16
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多