`mhook` is a small Node.js library that provides middleware-like hook functionality, particularly useful for structuring relations within entities in applications like ODMs or ORMs. It allows developers to define a set of named "actions" and then bind multiple hook functions to these actions. When an action is "triggered," all associated hooks are executed sequentially. Hooks can be asynchronous, supporting both traditional Node.js error-first callbacks and Promises for indicating completion or failure. The current stable version is 1.0.1. Its key differentiators include a simple API for sequential hook execution and built-in support for both callback and promise-based asynchronous operations, making it flexible for various async patterns. It focuses purely on the hooking mechanism without dictating how the hooked objects should behave beyond providing `on` and `trigger` methods.
npm install mhookVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to define actions, bind both callback-based and promise-based hook functions to an action, and then trigger that action, showing how arguments are passed and results are handled.
Ensure all asynchronous `on` handler functions either return a `Promise` that resolves upon completion, or accept a `done` callback as their last argument and invoke `done()` (or `done(error)`) when their operation is finished.
Ensure that individual hook functions are efficient. For potentially long-running tasks, consider offloading them to worker threads or processing them asynchronously outside the main hook chain, if their completion isn't strictly necessary before subsequent hooks.
Always define all possible action names in the array passed to the `Hook` constructor. Ensure consistency between declared actions and those used in `on()` and `trigger()` calls.
Inspect all functions added via `hook.on()` for the affected action. Verify that asynchronous hooks either `return new Promise(...)` or accept `done` as the last argument and invoke `done()` when their work is complete.
Use CommonJS `require()` syntax: `const { Hook } = require('mhook');` for named exports or `const mhook = require('mhook');` and then `mhook.Hook`.Ensure your hook function signature correctly accounts for the arguments you pass. If you pass `[obj]` and use a callback, the signature should be `function(obj, done)`. If you pass `[obj1, obj2]` and use a promise, it should be `function(obj1, obj2)`.
No dependency data recorded yet.