feathersjs / hooks

Async middleware for JavaScript and TypeScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow to change the order of middleware

daffl opened this issue · comments

This is a follow-up for feathersjs/feathers#1590 to discuss options for allowing to change the order of middleware. Registering new middleware is currently possible using registerMiddleware:

const { hooks, registerMiddleware, getMiddleware } = require('@feathersjs/hooks');

// Hooks can be used with a function like this:
const sayHello = hooks(async name => {
  return `Hello ${name}!`;
}, [
  logRuntime,
  validateName
]);

registerMiddleware(sayHello, [
  otherHook
]);

However, it currently appends otherHook to the existing chain. One improvement possible would be to add a setMiddleware that allows to replace all middleware in combination with getMiddleware like this:

const { hooks, setMiddleware, getMiddleware } = require('@feathersjs/hooks');

// Hooks can be used with a function like this:
const sayHello = hooks(async name => {
  return `Hello ${name}!`;
}, [
  logRuntime,
  validateName
]);

setMiddleware(sayHello, [
  otherHook,
  ...getMiddleware(sayHello)
]);

Now otherHook would run first and your middleware chains are still explicitly defined.

Additionally it is also possible to customize where middleware is coming from using the collect option.

setMiddleware(sayHello, registeredHooks => [
  otherHook,
  ...registeredHooks
]);

like setState from React ?