Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ $ npm install koa-compose

Compose the given middleware and return middleware.

### compose([a, b, c, ...], wrapper)

Compose the given middleware, wrap all in given wrapper, and return middleware.

## License

MIT
Expand Down
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ module.exports = compose
* of all those which are passed.
*
* @param {Array} middleware
* @param {Function} wrapper
* @return {Function}
* @api public
*/

function compose (middleware) {
function compose (middleware, wrapper) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
if (wrapper && typeof wrapper !== 'function') throw new TypeError('Profiler needs be a function!')
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}
Expand All @@ -37,7 +39,9 @@ function compose (middleware) {
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
const fn = middleware[i] || next
let fn
if (wrapper) fn = middleware[i] ? wrapper(middleware[i]) : next
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

haha why not just

let fn = middleware[i] || next
if (wrapper) fn = wrapper(fn)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want to wrap next.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

next is guaranteed to be a function in conformance with standard Koa practice. It's not coming from the user 90% of the time. If you use co.wrap as a wrapper, you don't want it processing next.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, also, a profiler shouldn't run on the next function, that just wouldn't make sense.

else fn = middleware[i] || next
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(context, function next () {
Expand Down