Package Exports
- before-after-hook
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (before-after-hook) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
before-after-hook
wrap methods with before/after hooks
Motivation
When events are not enough to integrate libraries into your application, the
authors expose methods like onPreSave or onPostAuth, so you can apply custom
logic for validation, authentication or logging. With before-after-hook I want
to create a generic API that can be used by module authors to expose
asynchronous before & after hooks for internal functionality.
The original motivation is coming from Hoodie’s architecture. For example, the logic for authentication is separated from local data persistence and we need to send local changes before allowing the user to sign out to prevent data loss. Or on the server, creating a session should fail based on custom logic provided by the app, like a failed payment.
Scope
before-after-hook aims to implement the minimal amount of functionality
required for asynchronous method hooks. It is using promises exclusively and
does not alter arguments.
Install
npm install before-after-hookFor download the latest before-after-hook.min.js.
Example
// instantiate hook API
var hook = new Hook()
// Create a hook
hook('get', getData)
.then(handleData)
.catch(handleGetError)
// register before/after hooks. The methods can be async by returning a Promise
hook.before('get', beforeGetData)
hook.after('get', afterGetData)The methods are executed in the following order, each waiting for the promise
of the previous method to resolve (in case a promise was returned):
beforeGetData, getData, afterGetData, handleData. If any of the methods
throws an error or returns a rejected promise, handleGetError gets called.
API
Constructor
The Hook constructor has no options and returns a hook instance with the
methods below
var hook = new Hook()hook.api
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
hook()
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
- Any of the before hooks, whichever rejects / throws first
method- Any of the after hooks, whichever rejects / throws first
Simple Example
hook('save', record, function (record) {
return store.save(record)
})
// shorter: hook('save', record, store.save)
hook.before('save', function addTimestamps (record) {
var 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)
})
})hook.before()
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 |
Callback to be executed before method. Called with the hook’s
options argument. Before hooks can mutate the passed options,
they will also be passed to the wrapped method as first argument
|
Yes |
Example
hook.before('save', function validate (record) {
if (!record.name) {
throw new Error('name property is required')
}
})hook.after()
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 |
Callback to be executed after method. Called with whatever
the hook’s method resolves with and 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)
}
})hook.remove.before()
Removes before hook for given name. Returns hook instance for chaining.
hook.remove.before(name, beforeHookMethod)| Argument | Type | Description | Required |
|---|---|---|---|
name |
String | Hook name, for example 'save' |
Yes |
beforeHookMethod |
Function |
Same function that was previously passed to hook.before()
|
Yes |
Example
hook.remove.before('save', validateRecord)hook.remove.after()
Removes after hook for given name. Returns hook instance for chaining.
hook.remove.after(name, afterHookMethod)| Argument | Type | Description | Required |
|---|---|---|---|
name |
String | Hook name, for example 'save' |
Yes |
afterHookMethod |
Function |
Same function that was previously passed to hook.after()
|
Yes |
Example
hook.remove.after('save', triggerEvents)See also
If before-after-hook is not for you, have a look at one of these alternatives:
- https://github.com/keystonejs/grappling-hook
- https://github.com/sebelga/promised-hooks
- https://github.com/bnoguchi/hooks-js
- https://github.com/cb1kenobi/hook-emitter