refactor: compose (#116)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent be40084 · Browse files · 3 files·+79 added−29 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+79 added−29 removed
- tests:+63 added−16 removed
- other:+16 added−13 removed
Provenance
- Commit
a66296b- Tree
3f9f40c- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
be40084
3 files changed+79 added−29 removed
modified:src/compose.test.ts+63 added-16 removed
123445567889101112132 unmodified lines161718191920212223242 unmodified lines2728293030313231343233363738343536373841424344453940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import { compose } from './compose'import { Context } from './context'
type C = { req: { [key: string]: string } res: { [key: string]: string } req: Record<string, string> res: Record<string, string>}
describe('compose middleware', () => {describe('compose', () => { const middleware: Function[] = []
const a = async (c: C, next: Function) => { c.req['log'] = 'log'2 unmodified lines middleware.push(a)
const b = async (c: C, next: Function) => { await next() c.res['headers'] = `${c.res.headers}-custom-header` c.res['headers'] = 'custom-header' } middleware.push(b)
const handler = async (c: C, next: Function) => {2 unmodified lines c.res = { message: 'new response' } } middleware.push(handler)
const request = {} const response = {}
it('Request', async () => { const c: C = { req: request, res: response } const c: C = { req: {}, res: {} } const composed = compose<C>(middleware) await composed(c) expect(c.req['log']).not.toBeNull() expect(c.req['log']).toBe('log message') const context = await composed(c) expect(context.req['log']).not.toBeNull() expect(context.req['log']).toBe('log message') }) it('Response', async () => { const c: C = { req: request, res: response } const composed = compose(middleware) await composed(c) expect(c.res['header']).not.toBeNull() expect(c.res['message']).toBe('new response') const c: C = { req: {}, res: {} } const composed = compose<C>(middleware) const context = await composed(c) expect(context.res['headers']).not.toBeNull() expect(context.res['headers']).toBe('custom-header') expect(context.res['message']).toBe('new response') })})
describe('compose with Context', () => { const middleware: Function[] = []
const req = new Request('http://localhost/') const c: Context = new Context(req) const onError = (error: Error, c: Context) => { return c.text('onError', 500) }
it('Error on handler', async () => { const handler = () => { throw new Error() }
const mHandler = async (c: Context, next: Function) => { await next() }
middleware.push(mHandler) middleware.push(handler)
const composed = compose<Context>(middleware, onError) const context = await composed(c) expect(context.res).not.toBeNull() expect(context.res.status).toBe(500) expect(await context.res.text()).toBe('onError') })
it('Error on middleware', async () => { const handler = (c: Context) => { return c.text('OK') }
const mHandler = async () => { throw new Error() }
middleware.push(mHandler) middleware.push(handler)
const composed = compose<Context>(middleware, onError) const context = await composed(c) expect(c.res).not.toBeNull() expect(c.res.status).toBe(500) expect(await context.res.text()).toBe('onError') })})modified:src/compose.ts+14 added-11 removed
123455679891011121413141617181920212223151617181920212223242526272829302 unmodified linesimport { Context } from './context'
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <T>(middleware: Function[], onError?: Function) => { const errors: Error[] = [] return function (context: T, next?: Function) { let index = -1 return dispatch(0) async function dispatch(i: number): Promise<object | void> { async function dispatch(i: number): Promise<T> { if (i <= index) return Promise.reject(new Error('next() called multiple times')) index = i let fn = middleware[i] if (i === middleware.length) fn = next if (!fn) return Promise.resolve() if (!fn) return context try { return Promise.resolve(fn(context, dispatch.bind(null, i + 1))).catch((e) => { errors.push(e) if (onError && context instanceof Context) { context.res = onError(errors[0], context) } else { throw errors[0] } }) return Promise.resolve(fn(context, dispatch.bind(null, i + 1))) .then(() => { return context }) .catch((err) => { if (onError && context instanceof Context) { context.res = onError(err, context) return context } else { throw err } }) } catch (err) { return Promise.reject(err) } }2 unmodified linesmodified:src/hono.ts+2 added-2 removed
166 unmodified lines167 const composed = compose<Context>(middleware, this.onError)168 const c = new Context(request, { env: env, event: event, res: null })169 c.notFound = () => this.notFound(c)170 171- await composed(c)171+ const context = await composed(c)172 173- return c.res173+ return context.res174 }175 176 async handleEvent(event: FetchEvent): Promise<Response> {177 return this.dispatch(event.request, {}, event)25 unmodified lines