Skip to content

Instantly share code, notes, and snippets.

@shanehh
Created March 10, 2022 07:36
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 shanehh/e0f89b38bc8ec0253900823c719eb881 to your computer and use it in GitHub Desktop.
Save shanehh/e0f89b38bc8ec0253900823c719eb881 to your computer and use it in GitHub Desktop.
const MiddlewarePipeline = () => {
const _middlewares = []
return {
apply: middleware => _middlewares.push(middleware),
run: function run (middlewares) {
if (!middlewares) {
// set for first time call `run`
middlewares = _middlewares
}
if (middlewares.length > 0) {
const next = () => run(middlewares.slice(1))
return middlewares[0](next)
} else {
return
}
}
}
}
;(main => {
const pip = MiddlewarePipeline()
// say hi
pip.apply(next => {
console.log('hello!')
next()
console.log('goodbye.')
})
// just wow~
pip.apply(next => {
console.log('wow')
next()
})
pip.run()
})()
@shanehh
Copy link
Author

shanehh commented Mar 10, 2022

outputs:

❯ node how-middleware-pipeline-works.js
hello!
wow
goodbye.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment