Last active
May 24, 2018 16:49
-
-
Save ricardograca/31dfebb71f8147fa40ec5cb2175b86c0 to your computer and use it in GitHub Desktop.
Loading Bookshelf models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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