Skip to content

Instantly share code, notes, and snippets.

@LucaColonnello
Created September 10, 2020 09:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LucaColonnello/8bdec6b79d6a83f9fc022ada65be150c to your computer and use it in GitHub Desktop.
Save LucaColonnello/8bdec6b79d6a83f9fc022ada65be150c to your computer and use it in GitHub Desktop.
Custom Express like middleware system
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' });
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