Skip to content

Instantly share code, notes, and snippets.

@danecando
Created June 3, 2016 01:40
Show Gist options
  • Save danecando/9dc700f65b27a7916c0afe691b763020 to your computer and use it in GitHub Desktop.
Save danecando/9dc700f65b27a7916c0afe691b763020 to your computer and use it in GitHub Desktop.
codes for my hapi-bookshelf plugin
'use strict';
const Joi = require('joi');
const U = require('./utils');
const Schema = require('./schema');
const Pkg = require('./package.json');
const internals = {};
internals.PLUGIN_NAME = Pkg.name;
exports.register = function (server, options, next) {
if (!options) throw new Error('Missing hapi-bookshelf plugin options');
const validation = Joi.validate(options, Schema.options);
if (!validation || validation.error) throw validation.error;
const models = {};
const opts = validation.value || options;
const config = (typeof opts.config === 'object') ? opts.config
: require(U.projectPath(opts.config))[opts.env];
const knex = require('knex')(config);
const bookshelf = require('bookshelf')(knex);
opts.excluded = U.toArray(opts.excluded);
const getFilePaths = U.getFiles.bind(null, opts.models);
const modelPaths = getFilePaths(opts.excluded);
U.toArray(opts.plugins).forEach((plugin) =>
plugin ? bookshelf.plugin(plugin) : plugin
);
if (opts.base) {
opts.excluded.push(opts.base);
models.Base = bookshelf.Model = require(U.projectPath(opts.base))(bookshelf);
} else {
models.Base = bookshelf.Model;
}
modelPaths.forEach((path) => {
const file = require(U.projectPath(path))(bookshelf);
Object.assign(models, file);
});
// add plugin globals
server.expose('bookshelf', bookshelf);
server.expose('knex', bookshelf.knex);
server.expose('models', models);
// @todo extend with helper fn's
// server.expose('api', Api);
next();
};
exports.register.attributes = {
pkg: Pkg
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment