Promised Hooks

raw JSON →
3.1.1 verified Sat Apr 25 auth: no javascript maintenance

Lightweight middleware utility that adds pre and post hooks to any function returning a Promise. Version 3.1.1 is the current stable release, last updated several years ago with no active development. It allows wrapping classes, functions, or objects to intercept Promise-returning methods, with support for argument overriding and post-hook response modification. Different from general middleware libraries like Express or Koa, it focuses specifically on Promise-based async flows and integrates hooks directly into existing classes or objects without requiring a framework.

error TypeError: MyClass.pre is not a function
cause The class/object was not wrapped with hooks.wrap() before calling pre/post.
fix
Add hooks.wrap(MyClass) before MyClass.pre('method', fn).
error Cannot read property 'then' of undefined
cause The hook function did not return a Promise or the target method is not async.
fix
Ensure every hook function returns a Promise (or is async).
error UnhandledPromiseRejectionWarning: [object Object]
cause A pre hook resolved with an object that is not the expected __override shape, causing the original method to receive the object instead of arguments.
fix
Use { __override: ... } pattern correctly; if you don't need override, resolve with undefined or a simple value.
gotcha The __override pattern in pre hooks replaces arguments entirely; if you resolve with an object that is not the expected shape, the original method may fail.
fix Ensure __override provides the exact arguments expected by the original method, either a single value or an array of arguments.
gotcha Post hooks can also use __override to replace the response, but if multiple post hooks do this, only the last hook's override takes effect.
fix Design post hooks to chain properly; consider not using __override in post hooks unless you intend to discard previous responses.
breaking Version 1.0.0 introduced a breaking API change: hooks.wrap() must now be called on the class/object before using pre/post, whereas earlier versions (if any) may have worked differently.
fix Always call hooks.wrap(MyClass) before adding any pre/post hooks.
npm install promised-hooks
yarn add promised-hooks
pnpm add promised-hooks

Demonstrates wrapping a class, adding pre hook to override arguments, and post hook to modify the response.

import hooks from 'promised-hooks';

class Service {
  async fetch(id) {
    return { id, data: 'original' };
  }
}

hooks.wrap(Service);

Service.pre('fetch', async function() {
  // this is the class instance
  console.log('pre hook called');
  // Override arguments: resolve with __override
  return { __override: [42] };
});

Service.post('fetch', async function(result) {
  result.modified = true;
  return result;
});

const service = new Service();
const result = await service.fetch(1);
console.log(result); // { id: 42, data: 'original', modified: true }