Code Monkey home page Code Monkey logo

bookshelf-modelbase's Introduction

bookshelf-modelbase

Build Status Code Climate Test Coverage Version Downloads

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 overriding bookshelf.Model, there is nothing you can do to your bookshelf instance that will break bookshelf-modelbase.

Features

  • Adds timestamps (created_at and updated_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, and destroy

Usage

var db        = require(knex)(require('./knexfile'));
var bookshelf = require('bookshelf')(db);
// Pass an initialized bookshelf instance
var ModelBase = require('bookshelf-modelbase')(bookshelf);
// Or initialize as a bookshelf plugin
bookshelf.plugin(require('bookshelf-modelbase').pluggable);

var User = ModelBase.extend({
  tableName: 'users'

  // validation is passed to Joi.object(), so use a raw object
  validate: {
    firstName: Joi.string()
  }
});

User.create({ firstName: 'Grayson' })
.then(function () {
  return User.findOne({ firstName: 'Grayson' }, { require: true });
})
.then(function (grayson) {
  // passes patch: true to .save() by default
  return User.update({ firstName: 'Basil' }, { id: grayson.id });
})
.then(function (basil) {
  return User.destroy({ id: basil.id });
})
.then(function () {
  return User.findAll();
})
.then(function (collection) {
  console.log(collection.models.length); // => 0
})

API

model.create

/**
  * Naive add - create and save a model based on data
  * @param {Object} data
  * @param {Object} options (optional)
  * @return {Promise(bookshelf.Model)} single Model
  */
create: function (data, options) {
  return this.forge(data)
  .save(null, options);
}

model.destroy

/**
  * Naive destroy
  * @param {Object} options
  * @return {Promise(bookshelf.Model)} empty Model
  */
destroy: function (options) {
  return this.forge({ [this.prototype.idAttribute]: options.id })
  .destroy(options);
}

model.findAll

/**
  * Naive findAll - fetches all data for `this`
  * @param {Object} options (optional)
  * @return {Promise(bookshelf.Collection)} Bookshelf Collection of all Models
  */
findAll: function (options) {
  return bookshelf.Collection.forge([], { model: this }).fetch(options);
}

model.findById

/**
 * Find a model based on it's ID
 * @param {String} id The model's ID
 * @param {Object} [options] Options used of model.fetch
 * @return {Promise(bookshelf.Model)}
 */
findById: function (id, options) {
  return this.findOne({ [this.prototype.idAttribute]: id }, options)
}

model.findOne

/**
  * Naive findOne - fetch data for `this` matching data
  * @param {Object} data
  * @param {Object} options (optional)
  * @return {Promise(bookshelf.Model)} single Model
  */
findOne: function (data, options) {
  return this.forge(data).fetch(options);
}

model.findOrCreate

/**
  * Find or create - try and find the model, create one if not found
  * @param {Object} data
  * @param {Object} options
  * @return {Promise(bookshelf.Model)} single Model
  */
findOrCreate: function (data, options) {
  var self = this;

  return self.findOne(data, options)
  .then(function (model) {
    return model ? model : self.create(data, options);
  })
}

model.update

/**
  * Naive update - update a model based on data
  * @param {Object} data
  * @param {Object} options
  * @return {Promise(bookshelf.Model)} edited Model
  */
update: function (data, options) {
  _.defaults(options, {
    patch: true
  });
  return this.forge({ [this.prototype.idAttribute]: options.id }).fetch(options)
  .then(function (model) {
    if (model) {
      return model.save(data, options);
    }
  })
}

bookshelf-modelbase's People

Contributors

alanhoff avatar bsiddiqui avatar graysonchao avatar rahulbir avatar vellotis avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.