Created
September 10, 2020 09:33
-
-
Save LucaColonnello/8bdec6b79d6a83f9fc022ada65be150c to your computer and use it in GitHub Desktop.
Custom Express like middleware system
This file contains 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
const task = (data) => { | |
console.log('perform task with', data); | |
}; | |
const middlewares = []; | |
middlewares.push((data, next) => { | |
console.log('add custom data', data); | |
next({ ...data, type: 'humanoid', power: 'pizza tasting' }); | |
}); | |
middlewares.push((data, next) => { | |
console.log('logger >', data); | |
next(); | |
}); | |
const taskWithMiddleware = withMiddlewares(task, middlewares); | |
taskWithMiddleware({ name: 'Luca' }); | |
This file contains 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
const withMiddlewares = (task, middlewares) => { | |
const decoratedNext = middlewares.reduceRight( | |
(next, middleware) => | |
(arg, overrideArg) => middleware( | |
overrideArg ?? arg, | |
next.bind(null, overrideArg ?? arg) | |
), | |
task | |
); | |
return decoratedNext; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment