Skip to content

Instantly share code, notes, and snippets.

@ricardograca
Last active May 24, 2018 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardograca/31dfebb71f8147fa40ec5cb2175b86c0 to your computer and use it in GitHub Desktop.
Save ricardograca/31dfebb71f8147fa40ec5cb2175b86c0 to your computer and use it in GitHub Desktop.
Loading Bookshelf models
/*
* This will load all model files that exist in the same directory and attach them to the `models` variable.
* You can then simply require this file whenever you need it in your application and access the model you
* need:
*
* var models = require('./models/index.js')
* var FooModel = models.FooModel
*/
var Bookshelf = require('bookshelf')
var fs = require('fs')
var path = require('path')
var _ = require('lodash')
var bookshelf
var knex
var models = module.exports = {}
function loadModel(file) {
var modelName = _.capitalize(path.basename(file, '.js'))
if (!models[modelName] && path.extname(file) === '.js' && file !== 'index.js')
models[modelName] = require(path.join(__dirname, file))(bookshelf)
}
try {
knex = require('knex')({ /* your config here*/ })
bookshelf = new Bookshelf(knex)
}
catch (exception) {
console.error(exception)
throw new Error('Can\'t connect to database')
}
fs.readdirSync(__dirname).forEach(loadModel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment