2022-01-05 10:41:29 +01:00
|
|
|
import { compose } from '../src/compose'
|
|
|
|
|
2022-01-26 14:11:11 +01:00
|
|
|
type C = {
|
|
|
|
req: { [key: string]: string }
|
|
|
|
res: { [key: string]: string }
|
2022-01-05 10:41:29 +01:00
|
|
|
}
|
2021-12-21 09:37:02 +01:00
|
|
|
|
|
|
|
describe('compose middleware', () => {
|
2022-01-05 10:41:29 +01:00
|
|
|
const middleware: Function[] = []
|
2021-12-21 09:37:02 +01:00
|
|
|
|
2022-01-05 10:41:29 +01:00
|
|
|
const a = async (c: C, next: Function) => {
|
2021-12-21 09:37:02 +01:00
|
|
|
c.req['log'] = 'log'
|
2022-01-03 10:11:46 +01:00
|
|
|
await next()
|
2021-12-21 09:37:02 +01:00
|
|
|
}
|
|
|
|
middleware.push(a)
|
|
|
|
|
2022-01-05 10:41:29 +01:00
|
|
|
const b = async (c: C, next: Function) => {
|
2022-01-03 10:11:46 +01:00
|
|
|
await next()
|
2022-01-05 10:41:29 +01:00
|
|
|
c.res['headers'] = `${c.res.headers}-custom-header`
|
2021-12-21 09:37:02 +01:00
|
|
|
}
|
|
|
|
middleware.push(b)
|
|
|
|
|
2022-01-05 10:41:29 +01:00
|
|
|
const handler = async (c: C, next: Function) => {
|
2021-12-21 09:37:02 +01:00
|
|
|
c.req['log'] = `${c.req.log} message`
|
2022-01-03 10:11:46 +01:00
|
|
|
await next()
|
2021-12-21 09:37:02 +01:00
|
|
|
c.res = { message: 'new response' }
|
|
|
|
}
|
|
|
|
middleware.push(handler)
|
|
|
|
|
|
|
|
const request = {}
|
|
|
|
const response = {}
|
|
|
|
|
2022-01-03 10:11:46 +01:00
|
|
|
it('Request', async () => {
|
2022-01-05 10:41:29 +01:00
|
|
|
const c: C = { req: request, res: response }
|
2021-12-21 09:37:02 +01:00
|
|
|
const composed = compose(middleware)
|
2022-01-03 10:11:46 +01:00
|
|
|
await composed(c)
|
2021-12-21 09:37:02 +01:00
|
|
|
expect(c.req['log']).not.toBeNull()
|
|
|
|
expect(c.req['log']).toBe('log message')
|
|
|
|
})
|
2022-01-03 10:11:46 +01:00
|
|
|
it('Response', async () => {
|
2022-01-05 10:41:29 +01:00
|
|
|
const c: C = { req: request, res: response }
|
2021-12-21 09:37:02 +01:00
|
|
|
const composed = compose(middleware)
|
2022-01-03 10:11:46 +01:00
|
|
|
await composed(c)
|
2021-12-21 09:37:02 +01:00
|
|
|
expect(c.res['header']).not.toBeNull()
|
|
|
|
expect(c.res['message']).toBe('new response')
|
|
|
|
})
|
|
|
|
})
|