Giter Club home page Giter Club logo

bookshelf-manager's Introduction

Build Status Dependencies devDependencies

Model & Collection manager for Bookshelf.js to make it easy to create & save deep, nested JSON structures from API requests.

Installation

npm install bookshelf-manager --save

Usage

  1. Register as a plugin in Bookshelf:

    bookshelf.plugin('bookshelf-manager');
    • Optionally, you can pass in an object with a root property to read models from a specified directory:

      bookshelf.plugin('bookshelf-manager', { root: 'path/to/models' });
  2. Register individual models (not required if you passed in a root model directory as above):

    bookshelf.manager.register(model, modelName);
  3. Use the methods on bookshelf.manager to create, fetch, and save models or collections with support for deeply-nested attributes. E.g.:

    return bookshelf.manager.create('car', {
      features: [
        { name: 'ABS', cost: '1250' },
        { name: 'GPS', cost: '500' }
      ],
      quantity: 1
    }).then(function(car) {
      // created car should now have the associated features
    });

API

In progress...

Changelog

  • v0.3.0 - Add setHasOne functionality (#12)
  • v0.2.1 - Several breaking changes occurred with this version due to updating devDependencies and peerDependencies:
    • Knex and Bookshelf updated their bluebird and lodash dependencies
    • Knex changed how undefined values are inserted
  • v0.1.0 - Reimplement as a plugin for Bookshelf/Knex 0.8.x
  • v0.0.10 - Enforce belongsToMany IDs
  • v0.0.9 - Destroy removed hasMany models
  • v0.0.8 - Fetch empty collections
  • v0.0.7 - Attempt to use existing, eager-loaded models rather than re-fetch
  • v0.0.6 - Ignore _pivot_ keys
  • v0.0.5 - Improve error handling for unintialized instances & missing files
  • v0.0.4 - Improve .attach and .detach
  • v0.0.3 - Add support for lazy-managed models.
  • v0.0.2 - If instanceof Bookshelf is not provided, instance from Bookshelf.initialize is used.
  • v0.0.1 - Initial Release.

Copyright (c) 2013 Eric Clemmons Licensed under the MIT license.

bookshelf-manager's People

Contributors

alechirsch avatar blah238 avatar ericclemmons avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

bookshelf-manager's Issues

Looking for Contributors / Owners

This project came about to satisfy the following need:

A way to save a new / existing entity & all related sub-entities with a single POST

And the crazy thing is, *it worked!!

However, we're exploring other options at my office since this went into production over a year ago, and have since stopped using Bookshelf.

Plus, I have a family and a full-time job, so I'm not really apologizing ;)

Therefore, respond to this thread with the following info for Github & NPM publishing rights:

  1. Github username (well, it'll be on the issue, but just to show you're serious :D)
  2. NPM email / user so I can give you npm publisher access.

If no one steps up, I'll mark this project as deprecated and let the community find alternatives.

setHasOne is undefined in manager.js

One of my relationships on a model uses the bookshelf hasOne relationship. This relationships type is not defined in bookshelf-manager.

Unhandled rejection TypeError: Cannot read property 'bind' of undefined
at Manager. (node_modules/bookshelf-manager/lib/manager.js:252:35)

I looked at the code and could not find a setHasOne function.

Cascading save not working

Hi there,

I am trying to perform a cascading save but not found any success yet:
In summary all I want to do it update the parent model and the child collection (add the new one remove the old not required ones and update what is updated). Excuse my code its just POC. Please help answer my query.

DB Config file

'use strict';

var knex = require('knex')({
    client: 'mysql',
    connection: {
        host     : 'localhost',
        user     : 'root',
        password : 'root',
        database : 'rocket-poc',
        charset  : 'utf8'
    }
});

module.exports = require('bookshelf')(knex);

Model Declarations

'use strict';

var bookshelf = require('./db-config');

bookshelf.plugin('bookshelf-manager');

exports.getOpportunityModel = function(){

    var Opportunity = bookshelf.Model.extend({
        tableName: 'opportunity',
        livingExpenses: function() {
            return this.hasMany(LivingExpenses);
        }
    });

    var LivingExpenses = bookshelf.Model.extend({
        tableName: 'living_expenses'
    });

    return {
        Opportunity:Opportunity,
        LivingExpenses:LivingExpenses

    };

};

The Consumer

'use strict';

var opty = require('./opportunityModel');

var bookshelf = require('./db-config');

bookshelf.plugin('bookshelf-manager');

exports.operations = function(){

    return new opty.getOpportunityModel().Opportunity.where('id', 1).fetch({withRelated: ['livingExpenses']})
        .then(function(opportunity){
            //console.log(opportunity.toJSON());
            var livingExp1 = {description: "some this", value: 900};
            var livingExp2 = {description: "some this", value: 1900};

            //var le = new opty.getOpportunityModel().LivingExpenses();

            //console.log(le);

            return opportunity;

        })
        .then(function(opportunity){
            //console.log(opportunity);

            var optyOriginal  = opportunity;

            //opportunity.livingExpenses().a;
            var livingExp1 = {description: "some this", value: 1900, opportunity_id: 1};
            var livingExp2 = {description: "some this", value: 2300, opportunity_id: 1};

            var optyEx = opportunity.related('livingExpenses').set([livingExp1, livingExp2]);

            console.log(opportunity.toJSON());

            //return opportunity.save(null, {withRelated: ['livingExpenses']});

            return bookshelf.manager.save(optyOriginal, optyEx.toJSON());





        }).then(function(model){

            console.log(JSON.stringify(model));

            return Promise.resolve("done");
        })
        .catch(function(err){
            console.error(err);
            return Promise.reject(err);
        });


};

Add `patch` method

The patch method should operate like save, except it should pre-load and compute the optimal diff for saving:

var diff = function(before, after) {
  var patch = after;

  if (angular.isArray(after)) {
    patch = [];
  } else if (angular.isObject(after)) {
    patch = {};
  }

  if (angular.isObject(before) && angular.isDefined(after)) {
    // Compute difference for changed properties
    angular.forEach(before, function(left, key) {
      if (!angular.isDefined(after[key])) {
        return false;
      }

      var right = after[key];

      if (angular.isArray(after) || !angular.equals(left, right) || key === 'id') {
        patch[key] = diff(left, right);
      }
    });

    // Add new properties to patch
    angular.forEach(after, function(right, key) {
      if (!angular.isDefined(before[key])) {
        patch[key] = right;
      }
    });
  }

  return patch;
};

The save method should no longer pre-fetch a deep tree, and only patch should do that for calculation only, then defer to save for the actual saving.

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.