Distopico Vegan 9e639edc8d | 6 years ago | |
---|---|---|
.. | ||
LICENSE | 6 years ago | |
README.md | 6 years ago | |
index.js | 6 years ago | |
package.json | 6 years ago |
asynchronous hooks for internal functionality
// instantiate hook API
const hook = new Hook()
// Create a hook
function getData (options) {
return hook('get', options, fetchFromDatabase)
.then(handleData)
.catch(handleGetError)
}
// register before/error/after hooks.
// The methods can be async or return a promise
hook.before('get', beforeHook)
hook.error('get', errorHook)
hook.after('get', afterHook)
getData({id: 123})
The methods are executed in the following order
beforeHook
fetchFromDatabase
afterHook
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:
hook.wrap('get', async (getData, options) => {
await beforeHook(options)
try {
const result = getData(options)
} catch (error) {
await errorHook(error, options)
}
await afterHook(result, options)
})
npm install before-after-hook
Or download the latest before-after-hook.min.js
.
The Hook
constructor has no options and returns a hook
instance with the
methods below
const hook = new Hook()
Use the api
property to return the public API:
That way you don’t need to expose the hook() method to consumers of your library
Invoke before and after hooks. Returns a promise.
hook(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
method
Simple Example
hook('save', record, function (record) {
return store.save(record)
})
// shorter: hook('save', record, store.save)
hook.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.
hook(['add', 'save'], record, function (record) {
return store.save(record)
})
hook.before('add', function addTimestamps (record) {
if (!record.type) {
throw new Error('type property is required')
}
})
hook.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:
hook('add', record, function (record) {
return hook('save', record, function (record) {
return store.save(record)
})
})
Add before hook for given name. Returns hook
instance for chaining.
hook.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
hook.before('save', function validate (record) {
if (!record.name) {
throw new Error('name property is required')
}
})
Add error hook for given name. Returns hook
instance for chaining.
hook.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
hook.error('save', function (error, options) {
if (error.ignore) return
throw error
})
Add after hook for given name. Returns hook
instance for chaining.
hook.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
hook.after('save', function (result, options) {
if (result.updatedAt) {
app.emit('update', result)
} else {
app.emit('create', result)
}
})
Add wrap hook for given name. Returns hook
instance for chaining.
hook.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
hook.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
Removes hook for given name. Returns hook
instance for chaining.
hook.remove(name, hookMethod)
Argument | Type | Description | Required |
---|---|---|---|
name |
String | Hook name, for example 'save' |
Yes |
beforeHookMethod |
Function |
Same function that was previously passed to hook.before() , hook.error() , hook.after() or hook.wrap()
|
Yes |
Example
hook.remove('save', validateRecord)
If before-after-hook
is not for you, have a look at one of these alternatives: