如何保证nodejs中的Knex连接

How to ensure the Knex connection in nodejs

我正在为我的项目使用 NodeJS、Express 和 MySQL,并希望将 Bookshelf ORM 与它一起使用。

Bookshelf 使用Knex 进行查询、建模,建议通过Knex 建立数据库连接(http://bookshelfjs.org/#installation)。

我在与 Knex 成功建立数据库连接时遇到问题。我只想在数据库连接成功时启动服务器,但它似乎在建立连接后没有提供任何东西(没有承诺或 属性)。

这是我一直在使用的代码。

import _knex from "knex"; // npm install knex --save
import _bookshelf from "bookshelf"; // npm install bookshelf --save

let knex = _knex({
    client: "mysql",
    connection: {
        host: "127.0.0.1",
        database: process.env.DB,
        user: process.env.DB_USERNAME,
        password: process.env.DB_PASSWORD
    },
    debug: true
});

let bookshelf = _bookshelf(knex);

module.exports.knex = knex;
module.exports.bookshelf = bookshelf;

更多参考: 还有一个名为 Sequelize 的 ORM,它提供 sequelize.authenticate() 其中 return Promise 并且可以用作 (http://docs.sequelizejs.com/en/latest/api/sequelize/#authenticate-promise )

sequelize.authenticate()
    .then( () => {
        console.log("Db successfully connected");
        app.listen(port, () => console.log(`App started at: ${port}`) );
    })
    .catch( err => console.log('Unable to connect to the database') );

我能想到的唯一解决方案是执行像 USE {DB_NAME} 这样的原始查询,并使用其输出来决定是否启动服务器。这个解决方案够好吗?

本周早些时候在 knex 问题跟踪器中对此进行了讨论。 https://github.com/tgriesser/knex/issues/1886

进行查询是检查是否可以连接到数据库的好方法。如果没有查询,池不需要创建任何初始连接(取决于池设置)。

您还可以连接池的 afterCreate 回调,以便在与数据库 (https://github.com/knex/documentation/pull/17/files) 建立新连接时通知您。

也许这可以给你的问题一些提示。

我最近在调试与 postgresql 数据库的错误 knex 连接,发现(使用您的 knex 变量)

knex.client.connectionSettings

包含一个带有连接,呃,设置的对象。 如果未建立连接则未设置。我不知道确切的设置时间所以我不知道这是否表示 intent 成功 。我是单步的。此外,这不是您使用的同一个客户端,所以 ymmv。但我会在客户端而不是 knex 中查找您想要的信息。

代码自行解释

const config = require("../../config");

const pgsql = require('knex')({
    client: 'pg',
    connection: {
        host: config.PGSQL_HOST,
        port: config.PGSQL_PORT,
        user: config.PGSQL_USER,
        password: config.PGSQL_PWD,
        database : config.PGSQL_DB
    },
    useNullAsDefault: true
});

pgsql.raw("SELECT 1").then(() => {
    console.log("PostgreSQL connected");
})
.catch((e) => {
    console.log("PostgreSQL not connected");
    console.error(e);
});

module.exports = pgsql;