Skip to content

Commit

Permalink
chore: allow the compose function to be configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
shfshanyue authored and miwnwski committed Jul 2, 2022
1 parent 30242ee commit 5e37230
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 1 deletion.
71 changes: 71 additions & 0 deletions __tests__/application/compose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@

'use strict'

const request = require('supertest')
const assert = require('assert')
const Koa = require('../..')

describe('app.compose', () => {
it('should work with default compose ', async () => {
const app = new Koa()
const calls = []

app.use((ctx, next) => {
calls.push(1)
return next().then(() => {
calls.push(4)
})
})

app.use((ctx, next) => {
calls.push(2)
return next().then(() => {
calls.push(3)
})
})

const server = app.listen()

await request(server)
.get('/')
.expect(404)

assert.deepStrictEqual(calls, [1, 2, 3, 4])
})

it('should work with configurable compose', async () => {
const calls = []
let count = 0
const app = new Koa({
compose (fns){
return async (ctx) => {
const dispatch = async () => {
count++
const fn = fns.shift()
fn && fn(ctx, dispatch)
}
dispatch()
}
}
})

app.use((ctx, next) => {
calls.push(1)
next()
calls.push(4)
})
app.use((ctx, next) => {
calls.push(2)
next()
calls.push(3)
})

const server = app.listen()

await request(server)
.get('/')

assert.deepStrictEqual(calls, [1, 2, 3, 4])
assert.equal(count, 3)
})
})
6 changes: 6 additions & 0 deletions __tests__/application/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ describe('app', () => {
assert.strictEqual(app.subdomainOffset, subdomainOffset)
})

it('should set compose from the constructor', () => {
const compose = () => (ctx) => {}
const app = new Koa({ compose })
assert.strictEqual(app.compose, compose)
})

it('should have a static property exporting `HttpError` from http-errors library', () => {
const CreateError = require('http-errors')

Expand Down
3 changes: 2 additions & 1 deletion lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ module.exports = class Application extends Emitter {
this.proxyIpHeader = options.proxyIpHeader || 'X-Forwarded-For'
this.maxIpsCount = options.maxIpsCount || 0
this.env = options.env || process.env.NODE_ENV || 'development'
this.compose = options.compose || compose
if (options.keys) this.keys = options.keys
this.middleware = []
this.context = Object.create(context)
Expand Down Expand Up @@ -132,7 +133,7 @@ module.exports = class Application extends Emitter {
*/

callback () {
const fn = compose(this.middleware)
const fn = this.compose(this.middleware)

if (!this.listenerCount('error')) this.on('error', this.onerror)

Expand Down

0 comments on commit 5e37230

Please sign in to comment.