Search code examples
node.jsbookshelf.jsknex.jskraken.js

How to configure Knex for Bookshelf with Kraken.js


I am trying to integrate Knex (which I used on a previous app that did not use kraken.js), but I need it now for my ORM (bookshelf.js). I came across this post while researching, but I'm still a little fuzzy. This is for a mysql DB.

Where should I create the connection so I can pass it to the bookshelf object for my models?


Solution

  • Just set it as a global object in your onconfig() handler. Something like this:

    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);
      }
    };
    

    When you need your bookshelf object to define your models, you can include it and it's ready to go:

    models/accounts.js

       var bs = require('../lib/bs')();
    
        var Account = bs.Model.extend({
          idAttribute: 'id',
          tableName: 'accounts'
        });
    
        module.exports = function AccountModel() {
          return Account;
        }
    

    There's other ways to do it, but this is clean and should suffice for what you need.