Hapi Bookshelf Models
The purpose of this plugin is to provide a convenient way to register Bookshelf.js models and expose them via a Hapi plugin.
Registering the Plugin
var Hapi = require('hapi');
var server = new Hapi.Server();
server.register([
{
register: require('hapi-bookshelf-models'),
options: {
knex: {
client: 'pg',
connection: {
host: 'localhost',
user: 'username',
password: 'password',
database: 'db_name',
port: 5432
}
},
plugins: ['registry'], // Required
models: '../path/to/models/directory',
base: require('../path/to/model/base') // optional
}
}
], function (err) {
// An error will be available here if anything goes wrong
});
// You can now access Bookshelf.js via server.plugins.bookshelf and
// models can be retrieved via server.plugins.bookshelf.model('ModelName')
Options
knex
Knex Confuration Objectplugins
Bookshelf.js Plugins the registry plugin is requiredmodels
directory where you Bookshelf.js models are definedbase
(optional) function that applies the Bookshelf.js extend method and returns the extended model, example below.
base
Example // Add timestamps to all models
base: function (bookshelf) {
return bookshelf.Model.extend({
hasTimestamps: true
});
}
# Defining Models
There is more extensive documentation about defining models for the _registry_ plugin on the [Bookshelf.js Wiki](https://github.com/tgriesser/bookshelf/wiki/Plugin:-Model-Registry). Below is an example of defining two related models that can be placed in the ```models``` directory referenced above.
```javascript
// user.js
module.exports = function (bookshelf) {
return bookshelf.extend({
tableName: 'users',
roles: function () {
return this.belongsToMany('Role');
}
});
};
// role.js
module.exports = function (bookshelf) {
return bookshelf.extend({
tableName: 'roles'
});
};
After loading these models you can access them via server.plugins.bookshelf.model('User')
and server.plugins.bookshelf.model('Role')
respectively.
Notes:
- Models will be registered and made available under the file name with the first character capitalized. For example
user.js
becomesUser
andblogPost.js
becomesBlogPost