Skip to content

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