Installations
npm install @poppinss/hooks
Releases
Update dependencies
Published on 14 Sept 2024
Update dependencies
Published on 28 Mar 2024
Updating dependencies
Published on 16 Dec 2023
Publish source maps and use TSC for generating types
Published on 06 Nov 2023
Breaking changes + Rewrite to ESM
Published on 14 Oct 2023
Add option to run hooks in reverse order
Published on 09 Oct 2023
Developer
poppinss
Developer Guide
Module System
ESM
Min. Node Version
>=18.16.0
Typescript Support
Yes
Node Version
20.17.0
NPM Version
10.8.2
Statistics
14 Stars
87 Commits
3 Forks
5 Watching
2 Branches
4 Contributors
Updated on 14 Sept 2024
Languages
TypeScript (99.68%)
JavaScript (0.32%)
Total Downloads
Cumulative downloads
Total Downloads
5,050,537
Last day
3.2%
9,486
Compared to previous day
Last week
7.9%
53,571
Compared to previous week
Last month
1.8%
222,151
Compared to previous month
Last year
51.5%
2,394,971
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
@poppinss/hooks
A simple yet effective implementation for executing hooks around an event.
This package is a zero-dependency implementation for running lifecycle hooks around an event. Following are some of the notable features.
- Register and run lifecycle hooks.
- Hooks can return cleanup functions that are executed to perform the cleanup.
- Super lightweight
Setup
Install the package from the npm packages registry.
1npm i @poppinss/hooks 2 3# yarn lovers 4yarn add @poppinss/hooks
And import the Hooks
class as follows.
1import Hooks from '@poppinss/hooks' 2 3const hooks = new Hooks() 4 5hooks.add('saving', function () { 6 console.log('called') 7}) 8 9// Execute hooks using runner 10await hooks.runner('saving').run()
Defining hooks
The hooks are defined using the hooks.add
method. The method accepts the event name and a callback function to execute.
1const hooks = new Hooks() 2 3hooks.add('saving', function () { 4 console.log('called') 5})
You can also define hook as an object with the name
and the handle
method property. This is usually helpful when you want to specify a custom name for the hook, or re-use the same handle method multiple times.
1const hooks = new Hooks() 2 3function handleSave() {} 4 5hooks.add('saving', { name: 'beforeSave', handle: handleSave }) 6hooks.add('creating', { name: 'beforeCreate', handle: handleSave })
The handle
method receives the first argument as the event name, followed by the rest of the arguments supplied during runtime.
Running hooks
You can execute hooks using the Hooks Runner. You can create a new runner instance by calling the hooks.runner
method and passing the event name for which you want to execute hooks.
1const hooks = new Hooks() 2 3const runner = hooks.runner('saving') 4await runner.run()
To run hooks in the reverse order, you can use the runner.runReverse
method.
1const hooks = new Hooks() 2 3const runner = hooks.runner('saving') 4await runner.runReverse()
Passing data to hooks
You can pass one or more arguments to the runner.run
method, which the runner will share with the hook callbacks. For example:
1const hooks = new Hooks() 2 3hooks.add('saving', function (model, transaction) {}) 4 5const runner = hooks.runner('saving') 6await runner.run(model, transaction)
Cleanup functions
Cleanup functions allow hooks to clean up after themselves after the main action finishes successfully or with an error. Let's consider a real-world example of saving a model to the database.
- You will first run the
saving
hooks. - Assume one of the
saving
hooks writes some files to the disk. - Next, you issue the insert query to the database, and the query fails.
- The hook that has written files to the disk would want to remove those files as the main operation got canceled with an error.
Following is how you can express that with cleanup functions.
1hooks.add('saving', function () { 2 await fs.writeFile() 3 4 // Return the cleanup function 5 return (error) => { 6 // In case of an error, remove the file 7 if (error) { 8 await fs.unlink() 9 } 10 } 11})
The code responsible for issuing the insert query should run hooks as follows.
1const runner = hooks.runner('saving') 2 3try { 4 await runner.run(model) 5 await model.save() 6} catch (error) { 7 // Perform cleanup and pass error 8 await runner.cleanup(error) 9 throw error 10} 11 12// Perform cleanup in case of success as well 13await runner.cleanup()
Note: The
runner.cleanup
method is idempotent. Therefore you can call it multiple times, yet it will run the underlying cleanup methods only once.
Run without hook handlers
You can exclude certain hook handlers from executing using the without
method.
In the following example, we run hooks without executing the generateDefaultAvatar
hook handler. As you can notice, you can specify the function name as a string.
1hooks.add('saving', function hashPassword() {}) 2hooks.add('saving', function generateDefaultAvatar() {}) 3 4await hooks.runner('saving').without(['generateDefaultAvatar']).run()
Event types
You can also specify the types of supported events and their arguments well in advance as follows.
The first step is to define a type for all the events.
1type Events = { 2 saving: [ 3 [BaseModel], // for hook handler 4 [error: Error | null, BaseModel], // for cleanup function 5 ] 6 finding: [ 7 [QueryBuilder], // for hook handler 8 [error: Error | null, QueryBuilder], // for cleanup function 9 ] 10}
And then pass it as a generic to the Hooks
class.
1const hooks = new Hooks<Events>()
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/poppinss/.github/docs/SECURITY.md:1
- Info: Found linked content: github.com/poppinss/.github/docs/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/poppinss/.github/docs/SECURITY.md:1
- Info: Found text in security policy: github.com/poppinss/.github/docs/SECURITY.md:1
Reason
3 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 2
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/labels.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/poppinss/hooks/labels.yml/7.x?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/labels.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/poppinss/hooks/labels.yml/7.x?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/poppinss/hooks/release.yml/7.x?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/poppinss/hooks/release.yml/7.x?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/release.yml:28
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/checks.yml:1
- Warn: topLevel 'contents' permission set to 'write': .github/workflows/release.yml:4
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 1 are checked with a SAST tool
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch '7.x'
Score
4.2
/10
Last Scanned on 2024-11-18
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