Skip to content

Instantly share code, notes, and snippets.

@hovissimo
Last active September 22, 2022 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hovissimo/ab7c5f33b871076ca3186e420918f4c9 to your computer and use it in GitHub Desktop.
Save hovissimo/ab7c5f33b871076ca3186e420918f4c9 to your computer and use it in GitHub Desktop.
Middleware function for Enhance.dev
/**
* applyMiddleware takes an array of middleware functions and returns a decorator that will apply
* the middleware functions in reverse order around the target function.
*
* Example
*
* const handleGet = async(req) => ({ ... })
* const mw1 = (next) => async (req) => await next(req) + " mw1"
* const mw2 = (next) => async (req) => await next(req) + " mw2"
* const mw3 = (next) => async (req) => await next(req) + " mw3"
* export const get = applyMiddleware([mw3, mw2, mw1])(handleGet)
*
* The last line in the example above is equivalent to
*
* export const get = async (req) = mw3(mw2(mw1(handleGet))))(req)
*
* The middleware functions are expected to look like
*
* (next) => async (req) => {
* // do stuff on the way in
* const result = await next(req)
* // do stuff on the way out
* return result
* }
*
*/
export const applyMiddleware = (middleware) => (handler) =>
middleware.reduceRight((next, fn) => fn(next), handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment