Skip to content

Commit

Permalink
fix(hooks): hooks can be binded as ioc bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Jun 30, 2017
1 parent 0d935a0 commit 46498e8
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/Lucid/Hooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/

const _ = require('lodash')
const { resolver } = require('@adonisjs/fold')
const CE = require('../../Exceptions')

/**
Expand Down Expand Up @@ -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)
}
}
}
Expand Down
64 changes: 63 additions & 1 deletion test/unit/hooks.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {}
Expand Down Expand Up @@ -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')
})
})

0 comments on commit 46498e8

Please sign in to comment.