Gathering detailed insights and metrics for before-after-hook
Gathering detailed insights and metrics for before-after-hook
Gathering detailed insights and metrics for before-after-hook
Gathering detailed insights and metrics for before-after-hook
wrap methods with before/after hooks
npm install before-after-hook
99.4
Supply Chain
99.5
Quality
75.9
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
81 Stars
153 Commits
19 Forks
6 Watching
4 Branches
8 Contributors
Updated on 25 Oct 2024
Minified
Minified + Gzipped
JavaScript (89.2%)
TypeScript (10.8%)
Cumulative downloads
Total Downloads
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
asynchronous hooks for internal functionality
Browsers |
Load before-after-hook directly from cdn.skypack.dev
|
---|---|
Node |
Install with
|
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 });
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 });
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});
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
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);
The Hook.Collection
constructor has no options and returns a hookCollection
instance with the
methods below
1const hookCollection = new Hook.Collection();
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
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
method
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);
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});
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});
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});
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
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);
This library contains type definitions for TypeScript.
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
.
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();
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.
If before-after-hook
is not for you, have a look at one of these alternatives:
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
4 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
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
Reason
project is not fuzzed
Details
Reason
Project has not signed or included provenance with any releases.
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
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