hookable icon indicating copy to clipboard operation
hookable copied to clipboard

Support chainable hooks

Open pi0 opened this issue 11 months ago • 1 comments

Describe the feature

Hookable hooks will be called sequentially by default with original arguments. But result of each step is not preserved.

We could export a built-in chainable hook runner.

Example from https://github.com/unjs/community/discussions/15 (@ChrisGV04)

  const chainableCaller = async (hooks, args) => {
      let hookResult: Order = args[0];

      for (const hook of hooks) {
        hookResult = await hook(hookResult);
      }

      return hookResult;
    }
  /** Before create hook */
  const orderData = await hooks.callHookWith(chainableCaller, 'orders:before-create', originalOrder);

Some ideas:

  • We could export a built-in chainableCaller
  • We could support hookable.callHookChained(name, <initial>) that chains first arg
  • Hooks can be registred as chainable <-- I prefer this most / to define strategy on register instead of use but needs few initial refactors

pi0 avatar Jan 21 '25 10:01 pi0

I like your preferred proposal to register a hook as chainable, since you should already know beforehand if you are going to need it or not.

But any of the three proposals look fine to me. Specially if we can achieve the same goal and not create any breaking changes.

ChrisGV04 avatar Jan 21 '25 15:01 ChrisGV04