diff --git a/src/Lucid/Hooks/index.js b/src/Lucid/Hooks/index.js index 55fd23f8..75c43236 100644 --- a/src/Lucid/Hooks/index.js +++ b/src/Lucid/Hooks/index.js @@ -10,6 +10,7 @@ */ const _ = require('lodash') +const { resolver } = require('@adonisjs/fold') const CE = require('../../Exceptions') /** @@ -153,7 +154,8 @@ class Hooks { * Execute all handlers in sequence */ for (let handler of allHandlers) { - await handler.handler(ctx) + const { method } = resolver.forDir('modelHooks').resolveFunc(handler.handler) + await method(ctx) } } } diff --git a/test/unit/hooks.spec.js b/test/unit/hooks.spec.js index 0970df85..25928ad8 100644 --- a/test/unit/hooks.spec.js +++ b/test/unit/hooks.spec.js @@ -12,8 +12,18 @@ const test = require('japa') const Hooks = require('../../src/Lucid/Hooks') const helpers = require('./helpers') +const { ioc } = require('@adonisjs/fold') +const { setupResolver } = require('@adonisjs/sink') + +test.group('Hooks', (group) => { + group.before(() => { + setupResolver() + }) + + group.beforeEach(() => { + ioc.restore() + }) -test.group('Hooks', () => { test('it should add handler for a hook', (assert) => { const hooks = new Hooks() const fn = function () {} @@ -145,4 +155,56 @@ test.group('Hooks', () => { await hooks.exec('create') assert.deepEqual(stack, [2, 3, 1]) }) + + test('define hook handler as a binding', async (assert) => { + const hooks = new Hooks() + const stack = [] + + ioc.fake('Foo', () => { + return { + bar () { + stack.push(1) + } + } + }) + + hooks.addHandler('save', '@provider:Foo.bar') + await hooks.exec('create') + assert.deepEqual(stack, [1]) + }) + + test('auto pic hook from pre-defined directory', async (assert) => { + const hooks = new Hooks() + const stack = [] + + ioc.fake('App/Models/Hooks/Foo', () => { + return { + bar () { + stack.push(1) + } + } + }) + + hooks.addHandler('save', 'Foo.bar') + await hooks.exec('create') + assert.deepEqual(stack, [1]) + }) + + test('hook class should have access to this', async (assert) => { + assert.plan(1) + const hooks = new Hooks() + + class Foo { + bar () { + assert.instanceOf(this, Foo) + } + } + + ioc.fake('App/Models/Hooks/Foo', () => { + return new Foo() + }) + + hooks.addHandler('save', 'Foo.bar') + await hooks.exec('create') + }) })