Skip to content
wrap methods with before/after hooks
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples
lib fix: hook passes option when no handlers are defined Jan 11, 2019
test
.gitignore chore(gitignore): initial version Dec 7, 2016
.travis.yml
LICENSE Updated license year to 2018 Jan 16, 2018
README.md feat: `new Hook.Singular` for better Typescript support (#52) Mar 4, 2019
index.d.ts feat: `new Hook.Singular` for better Typescript support (#52) Mar 4, 2019
index.js refactor: user var instead of const for now, update deprecation message Mar 4, 2019
package-lock.json chore(package): update lockfile package-lock.json Mar 20, 2019
package.json

README.md

before-after-hook

asynchronous hooks for internal functionality

npm downloads Build Status Coverage Status Greenkeeper badge

Usage

Singular hook

Recommended for TypeScript

// instantiate singular hook API
const hook = new Hook.Singular()

// Create a hook
function getData (options) {
  return hook(options, fetchFromDatabase)
    .then(handleData)
    .catch(handleGetError)
}

// register before/error/after hooks.
// The methods can be async or return a promise
hook.before(beforeHook)
hook.error(errorHook)
hook.after(afterHook)

getData({id: 123})

Hook collection

// instantiate hook collection API
const hookCollection = new Hook.Collection()

// Create a hook
function getData (options) {
  return hookCollection('get', options, fetchFromDatabase)
    .then(handleData)
    .catch(handleGetError)
}

// register before/error/after hooks.
// The methods can be async or return a promise
hookCollection.before('get', beforeHook)
hookCollection.error('get', errorHook)
hookCollection.after('get', afterHook)

getData({id: 123})

Hook.Singular vs Hook.Collection

There's no fundamental difference between the Hook.Singular and Hook.Collection hooks except for the fact that a hook from a collection requires you to pass along the name. Therefore the following explanation applies to both code snippets as described above.

The methods are executed in the following order

  1. beforeHook
  2. fetchFromDatabase
  3. afterHook
  4. getData

beforeHook can mutate options before it’s passed to fetchFromDatabase.

If an error is thrown in beforeHook or fetchFromDatabase then errorHook is called next.

If afterHook throws an error then handleGetError is called instead of getData.

If errorHook throws an error then handleGetError is called next, otherwise afterHook and getData.

You can also use hook.wrap to achieve the same thing as shown above (collection example):

hookCollection.wrap('get', async (getData, options) => {
  await beforeHook(options)

  try {
    const result = getData(options)
  } catch (error) {
    await errorHook(error, options)
  }

  await afterHook(result, options)
})

Install

npm install before-after-hook

Or download the latest before-after-hook.min.js.

API

Singular hook API

Singular constructor

The Hook.Singular constructor has no options and returns a hook instance with the methods below:

const hook = new Hook.Singular()

Using the singular hook is recommended for TypeScript

Singular API

The singular hook is a reference to a single hook. This means that there's no need to pass along any identifier (such as a name as can be seen in the Hook.Collection API).

The API of a singular hook is exactly the same as a collection hook and we therefore suggest you read the Hook.Collection API and leave out any use of the name argument. Just skip it like described in this example:

const hook = new Hook.Singular()

// good
hook.before(beforeHook)
hook.after(afterHook)
hook(options, fetchFromDatabase)

// bad
hook.before('get', beforeHook)
hook.after('get', afterHook)
hook('get', options, fetchFromDatabase)

Hook collection API

Collection constructor

The Hook.Collection constructor has no options and returns a hookCollection instance with the methods below

const hookCollection = new Hook.Collection()

hookCollection.api

Use the api property to return the public API:

That way you don’t need to expose the hookCollection() method to consumers of your library

hookCollection()

Invoke before and after hooks. Returns a promise.

hookCollection(nameOrNames, [options,] method)
Argument Type Description Required
name String or Array of Strings Hook name, for example 'save'. Or an array of names, see example below. Yes
options Object Will be passed to all before hooks as reference, so they can mutate it No, defaults to empty object ({})
method Function Callback to be executed after all before hooks finished execution successfully. options is passed as first argument Yes

Resolves with whatever method returns or resolves with. Rejects with error that is thrown or rejected with by

  1. Any of the before hooks, whichever rejects / throws first
  2. method
  3. Any of the after hooks, whichever rejects / throws first

Simple Example

hookCollection('save', record, function (record) {
  return store.save(record)
})
// shorter:  hookCollection('save', record, store.save)

hookCollection.before('save', function addTimestamps (record) {
  const now = new Date().toISOString()
  if (record.createdAt) {
    record.updatedAt = now
  } else {
    record.createdAt = now
  }
})

Example defining multiple hooks at once.

hookCollection(['add', 'save'], record, function (record) {
  return store.save(record)
})

hookCollection.before('add', function addTimestamps (record) {
  if (!record.type) {
    throw new Error('type property is required')
  }
})

hookCollection.before('save', function addTimestamps (record) {
  if (!record.type) {
    throw new Error('type property is required')
  }
})

Defining multiple hooks is helpful if you have similar methods for which you want to define separate hooks, but also an additional hook that gets called for all at once. The example above is equal to this:

hookCollection('add', record, function (record) {
  return hookCollection('save', record, function (record) {
    return store.save(record)
  })
})

hookCollection.before()

Add before hook for given name. Returns hookCollection instance for chaining.

hookCollection.before(name, method)
Argument Type Description Required
name String Hook name, for example 'save' Yes
method Function Executed before the wrapped method. Called with the hook’s options argument. Before hooks can mutate the passed options before they are passed to the wrapped method. Yes

Example

hookCollection.before('save', function validate (record) {
  if (!record.name) {
    throw new Error('name property is required')
  }
})

hookCollection.error()

Add error hook for given name. Returns hookCollection instance for chaining.

hookCollection.error(name, method)
Argument Type Description Required
name String Hook name, for example 'save' Yes
method Function Executed when an error occurred in either the wrapped method or a before hook. Called with the thrown error and the hook’s options argument. The first method which does not throw an error will set the result that the after hook methods will receive. Yes

Example

hookCollection.error('save', function (error, options) {
  if (error.ignore) return
  throw error
})

hookCollection.after()

Add after hook for given name. Returns hook instance for chaining.

hookCollection.after(name, method)
Argument Type Description Required
name String Hook name, for example 'save' Yes
method Function Executed after wrapped method. Called with what the wrapped method resolves with the hook’s options argument. Yes

Example

hookCollection.after('save', function (result, options) {
  if (result.updatedAt) {
    app.emit('update', result)
  } else {
    app.emit('create', result)
  }
})

hookCollection.wrap()

Add wrap hook for given name. Returns hookCollection instance for chaining.

hookCollection.wrap(name, method)
Argument Type Description Required
name String Hook name, for example 'save' Yes
method Function Receives both the wrapped method and the passed options as arguments so it can add logic before and after the wrapped method, it can handle errors and even replace the wrapped method altogether Yes

Example

hookCollection.wrap('save', async function (saveInDatabase, options) {
  if (!record.name) {
    throw new Error('name property is required')
  }

  try {
    const result = await saveInDatabase(options)

    if (result.updatedAt) {
      app.emit('update', result)
    } else {
      app.emit('create', result)
    }

    return result
  } catch (error) {
    if (error.ignore) return
    throw error
  }
})

See also: Test mock example

hookCollection.remove()

Removes hook for given name. Returns hookCollection instance for chaining.

hookCollection.remove(name, hookMethod)
Argument Type Description Required
name String Hook name, for example 'save' Yes
beforeHookMethod Function Same function that was previously passed to hookCollection.before(), hookCollection.error(), hookCollection.after() or hookCollection.wrap() Yes

Example

hookCollection.remove('save', validateRecord)

TypeScript

This library contains type definitions for TypeScript. When you use TypeScript we highly recommend using the Hook.Singular constructor for your hooks as this allows you to pass along type information for the options object. For example:

import {Hook} from 'before-after-hook'

interface Foo {
  bar: string
  num: number;
}

const hook = new Hook.Singular<Foo>();

hook.before(function (foo) {

  // typescript will complain about the following mutation attempts
  foo.hello = 'world'
  foo.bar = 123

  // yet this is valid
  foo.bar = 'other-string'
  foo.num = 123
})

const foo = hook({bar: 'random-string'}, function(foo) {
  // handle `foo`
  foo.bar = 'another-string'
})

// foo outputs
{
  bar: 'another-string',
  num: 123
}

An alternative import:

import {Singular, Collection} from 'before-after-hook'

const hook = new Singular<{foo: string}>();
const hookCollection = new Collection();

Upgrading to 1.4

Since version 1.4 the Hook constructor has been deprecated in favor of returning Hook.Singular in the next major release.

Version 1.4 is still 100% backwards-compatible, but if you want to continue using hook collections, we recommend using the Hook.Collection constructor instead before the next release.

For even more details, check out the PR.

See also

If before-after-hook is not for you, have a look at one of these alternatives:

License

Apache 2.0

You can’t perform that action at this time.