From 3fe059d9c35ff47455aae4c6adc9eb14299f24fc Mon Sep 17 00:00:00 2001 From: sebelga Date: Mon, 30 Jul 2018 21:20:46 +0200 Subject: [PATCH] fix(transaction-post-hooks): Add missing scope to post hooks inside a transaction #115 --- lib/model.js | 11 +++++++++-- test/model-test.js | 17 +++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/lib/model.js b/lib/model.js index b11e187..de92371 100755 --- a/lib/model.js +++ b/lib/model.js @@ -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')) { @@ -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(); @@ -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 + ); } } } diff --git a/test/model-test.js b/test/model-test.js index 527f833..b7730e7 100755 --- a/test/model-test.js +++ b/test/model-test.js @@ -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(); }); @@ -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(); }); @@ -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' } });