Last active
September 22, 2022 13:28
-
-
Save hovissimo/ab7c5f33b871076ca3186e420918f4c9 to your computer and use it in GitHub Desktop.
Middleware function for Enhance.dev
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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