Skip to content

Commit

Permalink
feat: add hooks.has to find if a hook already exists
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Feb 9, 2020
1 parent 0683b5d commit 845cc19
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ export class Hooks {
return handler
}

/**
* Returns a boolean whether a handler has been already registered or not
*/
public has (lifecycle: 'before' | 'after', action: string, handler: HooksHandler | string): boolean {
const handlers = this.hooks[lifecycle].get(action)
const resolvedHandler = this.resolveHandler(handler)
if (!handlers) {
return false
}

return handlers.has(resolvedHandler)
}

/**
* Register hook handler for a given event and lifecycle
*/
Expand Down
33 changes: 33 additions & 0 deletions test/hooks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,21 @@ test.group('Hooks', () => {
await hooks.exec('before', 'save', ['foo', 'bar'])
assert.deepEqual(stack, [])
})

test('find if a hook already exists', async (assert) => {
const stack: string[] = []
const hooks = new Hooks()

function beforeSave (): Promise<void> {
return new Promise((resolve) => {
stack.push('one')
setTimeout(resolve, 100)
})
}

hooks.add('before', 'save', beforeSave)
assert.isTrue(hooks.has('before', 'save', beforeSave))
})
})

test.group('Hooks | Ioc Resolver', () => {
Expand Down Expand Up @@ -243,4 +258,22 @@ test.group('Hooks | Ioc Resolver', () => {
await hooks.exec('before', 'save', ['foo', 'bar'])
assert.deepEqual(stack, [])
})

test('find if ioc container reference hook already exists', async (assert) => {
const stack: string[] = []

const ioc = new Ioc()
ioc.bind('User', () => {
return {
save () {
stack.push(String(stack.length + 1))
},
}
})

const hooks = new Hooks(ioc.getResolver())

hooks.add('before', 'save', 'User.save')
assert.isTrue(hooks.has('before', 'save', 'User.save'))
})
})

0 comments on commit 845cc19

Please sign in to comment.