如何确保nodejs中的Knex连接

问题描述 投票:7回答:1

我正在为我的项目使用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,它提供了返回Promise的sequelize.authenticate(),可以用作(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.js bookshelf.js
1个回答
7
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.