bookshelf-modelbase
Why
Bookshelf.js is awesome. However,
we found ourselves extending bookshelf.Model
for the same reasons over and
over - parsing and formatting (to and from DB) niceties, adding timestamps, and
validating data on save, for example. Since these are problems you'll likely
have to solve for most use cases of Bookshelf, it made sense to provide a
convenient set of core model features.
Please note
-
bookshelf-modelbase
will not force you to use it for all your models. If you want to use it for some and not others, nothing bad will happen. -
bookshelf-modelbase
requires you to pass in an initialized instance of bookshelf, meaning that you can configure bookshelf however you please. Outside of overridingbookshelf.Model
, there is nothing you can do to your bookshelf instance that will breakbookshelf-modelbase
.
Features
-
Adds timestamps (
created_at
andupdated_at
) -
Validate own attributes on save using Joi. You can pass in a validation object as a class attribute when you extend
bookshelf-modelbase
- see below for usage. -
Naive CRUD methods -
findAll
,findOne
,findOrCreate
,create
,update
, anddestroy
Usage
var db = ;var bookshelf = db;var Joi = ;// Pass an initialized bookshelf instancevar ModelBase = bookshelf;// Or initialize as a bookshelf pluginbookshelf; var User = ModelBase; User
API
model.create
/** * Insert a model based on data * @param * @param * @return {Promise(bookshelf.Model)} */ { return this;}
model.destroy
/** * Destroy a model by id * @param * @param * @param * @return {Promise(bookshelf.Model)} empty model */ { options = ; return this ;}
model.findAll
/** * Select a collection based on a query * @param * @param * @return {Promise(bookshelf.Collection)} Bookshelf Collection of Models */ { return this;}
model.findById
/** * Find a model based on it's ID * @param * @param * @return {Promise(bookshelf.Model)} */ { return this;}
model.findOne
/** * Select a model based on a query * @param * @param * @param * @return {Promise(bookshelf.Model)} */ { options = ; return this;}
model.findOrCreate
/** * Select a model based on data and insert if not found * @param * @param * @param * @return {Promise(bookshelf.Model)} single Model */ { return this ;}
model.update
/** * Update a model based on data * @param * @param * @param * @param * @param * @return {Promise(bookshelf.Model)} */ { options = ; return this ;}
model.upsert
/** * Select a model based on data and update if found, insert if not found * @param * @param * @param */ { return this ;}