Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 classes support of virtuals #103

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Conversation

mp-ffx
Copy link
Contributor

@mp-ffx mp-ffx commented Feb 1, 2018

Hi, I'm using bookshelfjs with ES6 classes, like:

class Test extends bookshelf.Model {
  get tableName() { 
    return 'tests'
  }
  get hasTimestamps() {
    return true
  }
  get virtuals() { 
    return {
      test: 'test'
    }
  }
}

Because getters aren't cloned by default, they get omitted when mapping the model.

@chamini2
Copy link
Collaborator

chamini2 commented Feb 1, 2018

I think the solution is not actually the best. This assumes there is a virtuals object to clone (which in turn assumes the virtuals plugin is enabled?).

Wouldn't it make sense to copy all getters? Not just this special case of the virtuals. You can see maybe how we could do this with: https://jsfiddle.net/vwb04d4f/6/.

By the way, add some tests for a bookshelf model with getters that should get copied and don't.

I hack a way for them to appear by doing the following:

App.Model.extend({
  tableName: 'tests',
  hasTimestamps: false,

  virtuals: {
    payment_total() {
      return this.get('price') * this.get('number');
    }
  },

  format(attrs) {
    return _.omit(attrs, 'payment_total');
  },

  initialize() {
    // Setting virtuals
    this.on('dbAssigned fetched', (model) => {
      model.attributes.payment_total = model.get('payment_total');
    });
    this.on('fetched:collection', (collection) => {
      collection.forEach((model) => {
        model.attributes.payment_total = model.get('payment_total');
      });
    });
  }
});

@mp-ffx
Copy link
Contributor Author

mp-ffx commented Feb 1, 2018

I added a check for the presence of the 'virtuals' key for the Model. I think it's enough to just copy that getter, since we just need the data which represents the model. All other getters are irrelevant i quess?

I wasn't quite sure how to test/create ES6 classes with Typescript, that's why I've added a second spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants