Skip to content

Commit

Permalink
fix(transaction-post-hooks): Add missing scope to post hooks inside a…
Browse files Browse the repository at this point in the history
… transaction

#115
  • Loading branch information
sebelga committed Jul 30, 2018
1 parent 7c06a92 commit 3fe059d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
11 changes: 9 additions & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,7 @@ class Model extends Entity {
* Add "post" hooks to a transaction
*/
static hooksTransaction(transaction, postHooks) {
const _this = this;
postHooks = arrify(postHooks);

if (!{}.hasOwnProperty.call(transaction, 'hooks')) {
Expand All @@ -641,7 +642,7 @@ class Model extends Entity {

transaction.execPostHooks = function executePostHooks() {
if (this.hooks.post) {
return this.hooks.post.reduce((promise, hook) => promise.then(hook), Promise.resolve());
return this.hooks.post.reduce((promise, hook) => promise.then(hook.bind(_this)), Promise.resolve());
}

return Promise.resolve();
Expand Down Expand Up @@ -839,7 +840,13 @@ class Model extends Entity {
if (transaction) {
// disable (post) hooks, we will only trigger them on transaction succceed
this.__hooksEnabled = false;
this.constructor.hooksTransaction(transaction, this.__posts ? this.__posts.save : undefined);
this.constructor.hooksTransaction.call(
_this,
transaction,
this.__posts
? this.__posts.save
: undefined
);
}
}
}
Expand Down
17 changes: 15 additions & 2 deletions test/model-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -845,7 +845,7 @@ describe('Model', () => {

it('should set "pre" hook scope to entity being deleted (1)', (done) => {
schema.pre('delete', function preDelete() {
expect(this instanceof Entity);
expect(this instanceof Entity).equal(true);
done();
return Promise.resolve();
});
Expand Down Expand Up @@ -892,7 +892,7 @@ describe('Model', () => {
schema.post('delete', function postDeleteHook({ key }) {
expect(key.constructor.name).equal('Key');
expect(key.id).equal(123);
expect(this instanceof Entity);
expect(this instanceof Entity).equal(true);
expect(this.entityKey).equal(key);
return Promise.resolve();
});
Expand Down Expand Up @@ -1564,6 +1564,19 @@ describe('Model', () => {
});
});

it('transaction.execPostHooks() should set scope to entity saved', (done) => {
schema.post('save', function preSave() {
expect(this instanceof Entity).equal(true);
expect(this.name).equal('John Jagger');
done();
});
ModelInstance = Model.compile('Blog', schema, gstore);
model = new ModelInstance({ name: 'John Jagger' });

model.save(transaction)
.then(() => transaction.execPostHooks());
});

it('if transaction.execPostHooks() is NOT called post middleware should not be called', () => {
const spyPost = sinon.stub().resolves(123);
schema = new Schema({ name: { type: 'string' } });
Expand Down

0 comments on commit 3fe059d

Please sign in to comment.