Skip to content

Commit

Permalink
Changed registry plugin to re-implement only the _relation method
Browse files Browse the repository at this point in the history
This way the registry plugin can be used in custom relations created with _relation
  • Loading branch information
chamini2 committed Jun 20, 2016
1 parent 0124c0b commit bb8300f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
24 changes: 13 additions & 11 deletions src/plugins/registry.js
Expand Up @@ -55,18 +55,20 @@ module.exports = function (bookshelf) {

const { Collection, Model } = bookshelf;

// Re-implement the `bookshelf.Model` relation methods to include a check for
// Re-implement the `bookshelf.Model` _relation method to include a check for
// the registered model.
_.each([
'belongsTo', 'belongsToMany', 'hasMany', 'hasOne', 'morphMany', 'morphOne',
'through'
], method => {
const original = Model.prototype[method];
Model.prototype[method] = function(Target) {
// The first argument is always a model, so resolve it and call the original method.
return original.apply(this, [resolveModel(Target)].concat(_.drop(arguments)));
};
});
const _relation = Model.prototype._relation;
Model.prototype._relation = function (method, Target) {
// The second argument is always a model, so resolve it and call the original method.
return _relation.apply(this, [method, resolveModel(Target)].concat(_.drop(arguments, 2)));
}

// The `through` method doesn't use `_relation` beneath, so we have to
// re-implement it specifically
const through = Model.prototype.through;
Model.prototype.through = function (Target) {
return through.apply(this, [resolveModel(Target)].concat(_.drop(arguments)));
}

// `morphTo` takes the relation name first, and then a variadic set of models so we
// can't include it with the rest of the relational methods.
Expand Down
10 changes: 5 additions & 5 deletions test/integration/plugins/registry.js
Expand Up @@ -6,17 +6,17 @@ module.exports = function(Bookshelf) {
describe('Model Registry', function() {

before(function() {
this.hasOne = sinon.spy(Bookshelf.Model.prototype, 'hasOne');
this._relation = sinon.spy(Bookshelf.Model.prototype, '_relation');
this.morphTo = sinon.spy(Bookshelf.Model.prototype, 'morphTo');
});

after(function() {
this.hasOne.restore();
this._relation.restore();
this.morphTo.restore();
});

beforeEach(function () {
this.hasOne.reset();
this._relation.reset();
this.morphTo.reset();
});

Expand Down Expand Up @@ -155,7 +155,7 @@ module.exports = function(Bookshelf) {

it('applies the resolved model to the original method', function() {
this.model._hasOne();
expect(this.hasOne).to.have.been.calledWith(this.relatedModel);
expect(this._relation).to.have.been.calledWith('hasOne', this.relatedModel);
});

it('allows for *-through relations', function() {
Expand Down Expand Up @@ -197,4 +197,4 @@ module.exports = function(Bookshelf) {
});

});
};
};

0 comments on commit bb8300f

Please sign in to comment.