Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async (ctx, next) => await next() #27

Merged
merged 9 commits into from
Oct 22, 2015
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,12 @@ function compose(middleware){
*/

return function (context, next) {
// last called middleware #
let index = -1
return dispatch(0)
function dispatch(i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
const fn = middleware[i] || next
if (!fn) return Promise.resolve()
try {
Expand Down
60 changes: 58 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,65 @@ describe('Koa Compose', function(){

return compose(stack.map(co.wrap))({}).then(function () {
throw 'promise was not rejected'
})
.catch(function (e) {
}).catch(function (e) {
e.should.be.instanceof(Error)
})
})

// https://github.com/koajs/compose/pull/27#issuecomment-143109739
it('should compose w/ other compositions', function() {
var called = [];

return compose([
compose([
(ctx, next) => {
called.push(1)
return next()
},
(ctx, next) => {
called.push(2)
return next()
}
]),
(ctx, next) => {
called.push(3)
return next()
}
])({}).then(() => assert.deepEqual(called, [1, 2, 3]))
})

it('should throw if next() is called multiple times', function() {
return compose([
co.wrap(function* (ctx, next) {
yield next()
yield next()
})
])({}).then(() => {
throw new Error('boom')
}, err => {
assert(/multiple times/.test(err.message))
})
})

it('should return a valid middleware', function () {
var val = 0
compose([
compose([
(ctx, next) => {
val++
return next()
},
(ctx, next) => {
val++
return next()
}
]),
(ctx, next) => {
val++
return next()
}
])({}).then(function () {
val.should.equal(3)
})
})
})