Loads Application Models (in api/models
) into the Bookshelf ORM; Integrates with trailpack-router to
generate Footprints for routes.
$ npm install --save trailpack-bookshelf
// config/main.js
module.exports = {
// ...
packs: [
require('trailpack-bookshelf')
]
}
// config/database.js
module.exports = {
stores: {
knexPostgres: {
orm: 'bookshelf',
client: 'pg',
/**
* knex connection object
* see: http://knexjs.org/#Installation-client
*/
connection: {
host: 'localhost',
user: 'admin',
password: '1234',
database: 'mydb'
}
}
},
/**
* Supported Migrate Settings:
* - none
* - drop
*/
migrate: 'none',
defaultStore: 'knexPostgres'
}
Models are constructed by bookshelf.Model.extend()
with values returned by schema()
as
the first argument and values from config()
as the second argument.
// api/models/User.js
class User extends Model {
static schema(app, table) {
//table definition for migrate='drop'
if (table) {
table.increments('id').primary();
table.string('name').notNullable();
return
} else {
// booskelf model prototypeProperties
return {
profile() {
return this.hasOne('profile');
}
}
}
}
}
// api/models/Profile.js
class Profile extends Model {
static config(app, bookshelf) {
// booskelf model classProperties
return {
tableName: 'user_profile'
};
}
static schema(app, table) {
//table definition for migrate='drop'
if (table) {
table.string('first_name');
table.string('last_name');
table.integer('user_id').notNullable().references('id').inTable('user');
return table;
} else {
// booskelf model prototypeProperties
return {
user() {
return this.belongsTo('User');
}
};
}
}
}
After the trailpack is initialized you can find all your bookshelf models in the this.app.orm
.
See bookshelf docs.
// api/services/UserService.js
module.exports = {
/**
* Fetches user with profile by id.
* @return Promise
* @example {
* name: 'jdoe',
* proflie: {
* first_name: 'John',
* last_name: 'Doe'
* }
* }
*/
fetchUserWithProfile(id) {
return this.orm.User.forge({ id: id }).fetch({ withRelated: 'profile' });
}
}
We love contributions! Please check out our Contributor's Guide for more information on how our projects are organized and how to get started.