wrap methods with before/after hooks
Installations
npm install before-after-hook
Score
99.4
Supply Chain
99.5
Quality
75.9
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Developer
Developer Guide
Module System
ESM
Min. Node Version
Typescript Support
Yes
Node Version
16.17.1
NPM Version
8.15.0
Statistics
81 Stars
153 Commits
19 Forks
6 Watching
4 Branches
8 Contributors
Updated on 25 Oct 2024
Bundle Size
1.36 kB
Minified
645.00 B
Minified + Gzipped
Languages
JavaScript (89.2%)
TypeScript (10.8%)
Total Downloads
Cumulative downloads
Total Downloads
1,252,583,412
Last day
-7.1%
1,635,900
Compared to previous day
Last week
3.9%
9,758,327
Compared to previous week
Last month
11%
39,578,143
Compared to previous month
Last year
20.5%
369,445,327
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
before-after-hook
asynchronous hooks for internal functionality
Usage
Browsers |
Load before-after-hook directly from cdn.skypack.dev
|
---|---|
Node |
Install with
|
Singular hook
1// instantiate singular hook API 2const hook = new Hook.Singular(); 3 4// Create a hook 5async function getData(options) { 6 try { 7 const result = await hook(fetchFromDatabase, options); 8 return handleData(result); 9 } catch (error) { 10 return handleGetError(error); 11 } 12} 13 14// register before/error/after hooks. 15// The methods can be async or return a promise 16hook.before(beforeHook); 17hook.error(errorHook); 18hook.after(afterHook); 19 20getData({ id: 123 });
Hook collection
1// instantiate hook collection API
2const hookCollection = new Hook.Collection();
3
4// Create a hook
5async function getData(options) {
6 try {
7 const result = await hookCollection("get", fetchFromDatabase, options);
8 return handleData(result);
9 } catch (error) {
10 return handleGetError(error);
11 }
12}
13
14// register before/error/after hooks.
15// The methods can be async or return a promise
16hookCollection.before("get", beforeHook);
17hookCollection.error("get", errorHook);
18hookCollection.after("get", afterHook);
19
20getData({ 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
beforeHook
fetchFromDatabase
afterHook
handleData
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 handleData
.
If errorHook
throws an error then handleGetError
is called next, otherwise
afterHook
and handleData
.
You can also use hook.wrap
to achieve the same thing as shown above (collection example):
1hookCollection.wrap("get", async (getData, options) => {
2 await beforeHook(options);
3
4 try {
5 const result = getData(options);
6 } catch (error) {
7 await errorHook(error, options);
8 }
9
10 await afterHook(result, options);
11});
API
Singular hook API
- Singular constructor
- hook.api
- hook()
- hook.before()
- hook.error()
- hook.after()
- hook.wrap()
- hook.remove()
Singular constructor
The Hook.Singular
constructor has no options and returns a hook
instance with the
methods below:
1const 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:
1const hook = new Hook.Singular(); 2 3// good 4hook.before(beforeHook); 5hook.after(afterHook); 6hook(fetchFromDatabase, options); 7 8// bad 9hook.before("get", beforeHook); 10hook.after("get", afterHook); 11hook("get", fetchFromDatabase, options);
Hook collection API
- Collection constructor
- hookCollection.api
- hookCollection()
- hookCollection.before()
- hookCollection.error()
- hookCollection.after()
- hookCollection.wrap()
- hookCollection.remove()
Collection constructor
The Hook.Collection
constructor has no options and returns a hookCollection
instance with the
methods below
1const hookCollection = new Hook.Collection();
hookCollection.api
Use the api
property to return the public API:
- hookCollection.before()
- hookCollection.after()
- hookCollection.error()
- hookCollection.wrap()
- hookCollection.remove()
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.
1hookCollection(nameOrNames, method /*, options */);
Argument | Type | Description | Required |
---|---|---|---|
name | String or Array of Strings | Hook name, for example 'save' . Or an array of names, see example below. | Yes |
method | Function | Callback to be executed after all before hooks finished execution successfully. options is passed as first argument | Yes |
options | Object | Will be passed to all before hooks as reference, so they can mutate it | No, defaults to empty object ({} ) |
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
1hookCollection( 2 "save", 3 (record) => { 4 return store.save(record); 5 }, 6 record 7); 8// shorter: hookCollection('save', store.save, record) 9 10hookCollection.before("save", function addTimestamps(record) { 11 const now = new Date().toISOString(); 12 if (record.createdAt) { 13 record.updatedAt = now; 14 } else { 15 record.createdAt = now; 16 } 17});
Example defining multiple hooks at once.
1hookCollection( 2 ["add", "save"], 3 (record) => { 4 return store.save(record); 5 }, 6 record 7); 8 9hookCollection.before("add", function addTimestamps(record) { 10 if (!record.type) { 11 throw new Error("type property is required"); 12 } 13}); 14 15hookCollection.before("save", function addTimestamps(record) { 16 if (!record.type) { 17 throw new Error("type property is required"); 18 } 19});
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:
1hookCollection( 2 "add", 3 (record) => { 4 return hookCollection( 5 "save", 6 (record) => { 7 return store.save(record); 8 }, 9 record 10 ); 11 }, 12 record 13);
hookCollection.before()
Add before hook for given name.
1hookCollection.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
1hookCollection.before("save", function validate(record) { 2 if (!record.name) { 3 throw new Error("name property is required"); 4 } 5});
hookCollection.error()
Add error hook for given name.
1hookCollection.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
1hookCollection.error("save", (error, options) => { 2 if (error.ignore) return; 3 throw error; 4});
hookCollection.after()
Add after hook for given name.
1hookCollection.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
1hookCollection.after("save", (result, options) => { 2 if (result.updatedAt) { 3 app.emit("update", result); 4 } else { 5 app.emit("create", result); 6 } 7});
hookCollection.wrap()
Add wrap hook for given name.
1hookCollection.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
1hookCollection.wrap("save", async (saveInDatabase, options) => { 2 if (!record.name) { 3 throw new Error("name property is required"); 4 } 5 6 try { 7 const result = await saveInDatabase(options); 8 9 if (result.updatedAt) { 10 app.emit("update", result); 11 } else { 12 app.emit("create", result); 13 } 14 15 return result; 16 } catch (error) { 17 if (error.ignore) return; 18 throw error; 19 } 20});
See also: Test mock example
hookCollection.remove()
Removes hook for given name.
1hookCollection.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
1hookCollection.remove("save", validateRecord);
TypeScript
This library contains type definitions for TypeScript.
Type support for Singular
:
1import Hook from "before-after-hook"; 2 3type TOptions = { foo: string }; // type for options 4type TResult = { bar: number }; // type for result 5type TError = Error; // type for error 6 7const hook = new Hook.Singular<TOptions, TResult, TError>(); 8 9hook.before((options) => { 10 // `options.foo` has `string` type 11 12 // not allowed 13 options.foo = 42; 14 15 // allowed 16 options.foo = "Forty-Two"; 17}); 18 19const hookedMethod = hook( 20 (options) => { 21 // `options.foo` has `string` type 22 23 // not allowed, because it does not satisfy the `R` type 24 return { foo: 42 }; 25 26 // allowed 27 return { bar: 42 }; 28 }, 29 { foo: "Forty-Two" } 30);
You can choose not to pass the types for options, result or error. So, these are completely valid:
1const hook = new Hook.Singular<O, R>(); 2const hook = new Hook.Singular<O>(); 3const hook = new Hook.Singular();
In these cases, the omitted types will implicitly be any
.
Type support for Collection
:
Collection
also has strict type support. You can use it like this:
1import { Hook } from "before-after-hook"; 2 3type HooksType = { 4 add: { 5 Options: { type: string }; 6 Result: { id: number }; 7 Error: Error; 8 }; 9 save: { 10 Options: { type: string }; 11 Result: { id: number }; 12 }; 13 read: { 14 Options: { id: number; foo: number }; 15 }; 16 destroy: { 17 Options: { id: number; foo: string }; 18 }; 19}; 20 21const hooks = new Hook.Collection<HooksType>(); 22 23hooks.before("destroy", (options) => { 24 // `options.id` has `number` type 25}); 26 27hooks.error("add", (err, options) => { 28 // `options.type` has `string` type 29 // `err` is `instanceof Error` 30}); 31 32hooks.error("save", (err, options) => { 33 // `options.type` has `string` type 34 // `err` has type `any` 35}); 36 37hooks.after("save", (result, options) => { 38 // `options.type` has `string` type 39 // `result.id` has `number` type 40});
You can choose not to pass the types altogether. In that case, everything will implicitly be any
:
1const hook = new Hook.Collection();
Alternative imports:
1import { Singular, Collection } from "before-after-hook"; 2 3const hook = new Singular(); 4const hooks = new Collection();
Upgrading to 1.4
Since version 1.4 the Hook
constructor has been deprecated in favor of returning Hook.Singular
in an upcoming breaking 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:
- https://github.com/keystonejs/grappling-hook
- https://github.com/sebelga/promised-hooks
- https://github.com/bnoguchi/hooks-js
- https://github.com/cb1kenobi/hook-emitter
License
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
- Info: security policy file detected: .github/SECURITY.md:1
- Info: Found linked content: .github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/SECURITY.md:1
- Info: Found text in security policy: .github/SECURITY.md:1
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0
Reason
packaging workflow detected
Details
- Info: Project packages its releases by way of GitHub Actions.: .github/workflows/release.yml:10
Reason
4 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/release.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/release.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:36: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:37: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/update-prettier.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/update-prettier.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/update-prettier.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/gr2m/before-after-hook/update-prettier.yml/main?enable=pin
- Info: 0 out of 8 GitHub-owned GitHubAction dependencies pinned
- Info: 4 out of 4 npmCommand dependencies pinned
Reason
Found 2/15 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/release.yml:1
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Warn: no topLevel permission defined: .github/workflows/update-prettier.yml:1
- Info: no jobLevel write permissions found
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
Project has not signed or included provenance with any releases.
Details
- Warn: release artifact v2.2.2 not signed: https://api.github.com/repos/gr2m/before-after-hook/releases/44134271
- Warn: release artifact v2.2.2 does not have provenance: https://api.github.com/repos/gr2m/before-after-hook/releases/44134271
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 21 are checked with a SAST tool
Score
4.3
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More