如何使用 Kraken.js 配置 Knex for Bookshelf

How to configure Knex for Bookshelf with Kraken.js

我正在尝试集成 Knex(我在之前未使用 kraken.js 的应用程序中使用过),但我现在需要它用于我的 ORM (bookshelf.js)。我在研究时遇到了 this post,但我仍然有点模糊。这是针对 mysql 数据库的。

我应该在哪里创建连接以便我可以将它传递给我的模型的书架对象?

只需在您的 onconfig() 处理程序中将其设置为全局对象。像这样:

config.json:

//...
"databaseConfig": {
  "host": // db host
  "database": // db name
  "user": //db user
  "password": //db pass
},

lib/bs.js

var bookshelf = require('bookshelf')(global.db);
module.exports = function Bookshelf() {
  return bookshelf;
};

index.js:

var options = {
  onconfig: function(config, next) {
    global.db = require('knex')({
      client: 'mysql',
      connection: config.get('databaseConfig')
    });

    next(null, config);
  }
};

当你需要你的书架对象来定义你的模型时,你可以包含它并且它已经准备好了:

models/accounts.js

   var bs = require('../lib/bs')();

    var Account = bs.Model.extend({
      idAttribute: 'id',
      tableName: 'accounts'
    });

    module.exports = function AccountModel() {
      return Account;
    }

还有其他方法可以做到这一点,但这很干净,应该足以满足您的需要。