refactor(compose): remove unnecessary complexity and improve testing (#3932)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(compose): remove unnecessary complexity and improve testing * test: add tests
authored by EdamAmex · committed by GitHub · parent df33970 · Browse files · 4 files·+168 added−178 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+168 added−178 removed
- tests:+151 added−139 removed
- other:+17 added−39 removed
Provenance
- Commit
c08a2a7- Tree
0358071- Author
EdamAmex <121654029+EdamAme-x@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
df33970
4 files changed+168 added−178 removed
modified:src/middleware/combine/index.ts+1 added-1 removed
97 unmodified lines989910010110210210310410510659 unmodified lines97 unmodified lines */export const every = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => { return async function every(c, next) { const currentRouteIndex = c.req.routeIndex await compose<Context>( await compose( middleware.map((m) => [ [ async (c: Context, next: Next) => { c.req.routeIndex = currentRouteIndex // should be unchanged in this context59 unmodified linesmodified:src/compose.test.ts+151 added-139 removed
1 import { compose } from './compose'2 import { Context } from './context'3 import type { Params } from './router'4+import type { Next } from './types'5 5-type C = {6- req: Record<string, string>7- res: Record<string, string>8- finalized: boolean9-}10-6 type MiddlewareTuple = [[Function, unknown], Params]7 8 class ExpectedError extends Error {}9 3 unmodified lines13 14 describe('compose', () => {15 const middleware: MiddlewareTuple[] = []16 22- const a = async (c: C, next: Function) => {23- c.req['log'] = 'log'17+ const a = async (c: Context, next: Next) => {18+ c.set('log', 'log')19 await next()20 }21 27- const b = async (c: C, next: Function) => {22+ const b = async (c: Context, next: Next) => {23 await next()29- c.res['headers'] = 'custom-header'24+ c.header('x-custom-header', 'custom-header')25 }26 32- const c = async (c: C, next: Function) => {33- c.req['xxx'] = 'yyy'27+ const c = async (c: Context, next: Next) => {28+ c.set('xxx', 'yyy')29 await next()35- c.res['zzz'] = c.req['xxx']30+ c.set('zzz', 'xxx')31 }32 38- const handler = async (c: C, next: Function) => {39- c.req['log'] = `${c.req.log} message`33+ const handler = async (c: Context, next: Next) => {34+ c.set('log', `${c.get('log')} message`)35 await next()41- c.res = { message: 'new response' }36+ return c.json({ message: 'new response' })37 }38 39 middleware.push(buildMiddlewareTuple(a))40 middleware.push(buildMiddlewareTuple(b))41 middleware.push(buildMiddlewareTuple(c))42 middleware.push(buildMiddlewareTuple(handler))43 44 it('Request', async () => {50- const c: C = { req: {}, res: {}, finalized: false }51- const composed = compose<C>(middleware)52- const context = await composed(c)53- expect(context.req['log']).not.toBeNull()54- expect(context.req['log']).toBe('log message')55- expect(context.req['xxx']).toBe('yyy')45+ const composed = compose(middleware)46+ const context = await composed(new Context(new Request('http://localhost/')))47+ expect(context.get('log')).not.toBeNull()48+ expect(context.get('log')).toBe('log message')49+ expect(context.get('xxx')).toBe('yyy')50 })51 it('Response', async () => {58- const c: C = { req: {}, res: {}, finalized: false }59- const composed = compose<C>(middleware)60- const context = await composed(c)61- expect(context.res['headers']).not.toBeNull()62- expect(context.res['headers']).toBe('custom-header')63- expect(context.res['message']).toBe('new response')64- expect(context.res['zzz']).toBe('yyy')52+ const composed = compose(middleware)53+ const context = await composed(new Context(new Request('http://localhost/')))54+ expect(context.res.headers.get('x-custom-header')).not.toBeNull()55+ expect(context.res.headers.get('x-custom-header')).toBe('custom-header')56+ expect((await context.res.json())['message']).toBe('new response')57+ expect(context.get('zzz')).toBe('xxx')58 })59 })60 61 describe('compose with returning a promise, non-async function', () => {62 const handlers: MiddlewareTuple[] = [63 buildMiddlewareTuple(() => {64 return new Promise((resolve) =>65 setTimeout(() => {73- resolve({ message: 'new response' })74- }, 1)66+ resolve(67+ new Response(JSON.stringify({ message: 'new response' }), {68+ headers: {69+ 'Content-Type': 'application/json',70+ },71+ })72+ )73+ })74 )75 }),76 ]77 78 it('Response', async () => {80- const c: C = { req: {}, res: {}, finalized: false }81- const composed = compose<C>(handlers)82- const context = await composed(c)83- expect(context.res['message']).toBe('new response')79+ const composed = compose(handlers)80+ const context = await composed(new Context(new Request('http://localhost/')))81+ expect((await context.res.json())['message']).toBe('new response')82 })83 })84 85 describe('Handler and middlewares', () => {1 unmodified line87 88 const req = new Request('http://localhost/')89 const c: Context = new Context(req)90 93- const mHandlerFoo = async (c: Context, next: Function) => {91+ const mHandlerFoo = async (c: Context, next: Next) => {92 c.req.raw.headers.append('x-header-foo', 'foo')93 await next()94 }95 98- const mHandlerBar = async (c: Context, next: Function) => {96+ const mHandlerBar = async (c: Context, next: Next) => {97 await next()98 c.header('x-header-bar', 'bar')99 }100 6 unmodified lines107 middleware.push(buildMiddlewareTuple(mHandlerBar))108 middleware.push(buildMiddlewareTuple(handler))109 110 it('Should return 200 Response', async () => {113- const composed = compose<Context>(middleware)111+ const composed = compose(middleware)112 const context = await composed(c)113 const res = context.res114 expect(res).not.toBeNull()115 expect(res.status).toBe(200)9 unmodified lines125 const c: Context = new Context(req)126 const handler = (c: Context) => {127 return c.text('Hello')128 }131- const mHandler = async (_c: Context, next: Function) => {129+ const mHandler = async (_c: Context, next: Next) => {130 await next()131 }132 133 middleware.push(buildMiddlewareTuple(handler))134 middleware.push(buildMiddlewareTuple(mHandler))135 136 it('Should return 200 Response', async () => {139- const composed = compose<Context>(middleware)137+ const composed = compose(middleware)138 const context = await composed(c)139 expect(context.res).not.toBeNull()140 expect(context.res.status).toBe(200)141 expect(await context.res.text()).toBe('Hello')9 unmodified lines151 }152 const onNotFoundAsync = async (c: Context) => {153 return c.text('onNotFoundAsync', 404)154 }157- const mHandler = async (_c: Context, next: Function) => {155+ const mHandler = async (_c: Context, next: Next) => {156 await next()157 }158 159 middleware.push(buildMiddlewareTuple(mHandler))160 161 it('Should return 404 Response', async () => {162 const c: Context = new Context(req)165- const composed = compose<Context>(middleware, undefined, onNotFound)163+ const composed = compose(middleware, undefined, onNotFound)164 const context = await composed(c)165 expect(context.res).not.toBeNull()166 expect(context.res.status).toBe(404)167 expect(await context.res.text()).toBe('onNotFound')1 unmodified line169 })170 171 it('Should return 404 Response - async handler', async () => {172 const c: Context = new Context(req)175- const composed = compose<Context>(middleware, undefined, onNotFoundAsync)173+ const composed = compose(middleware, undefined, onNotFoundAsync)174 const context = await composed(c)175 expect(context.res).not.toBeNull()176 expect(context.res.status).toBe(404)177 expect(await context.res.text()).toBe('onNotFoundAsync')8 unmodified lines186 const c: Context = new Context(req)187 const handler = (c: Context) => {188 return c.text('Hello')189 }192- const mHandler = async (c: Context, next: Function) => {190+ const mHandler = async (c: Context, next: Next) => {191 await next()192 c.res = new Response('Not authorized', { status: 401 })193 }194 195 middleware.push(buildMiddlewareTuple(mHandler))196 middleware.push(buildMiddlewareTuple(handler))197 198 it('Should return 401 Response', async () => {201- const composed = compose<Context>(middleware)199+ const composed = compose(middleware)200 const context = await composed(c)201 expect(context.res).not.toBeNull()202 expect(context.res.status).toBe(401)203 expect(await context.res.text()).toBe('Not authorized')9 unmodified lines213 const handler = (c: Context) => {214 const message = c.req.header('x-custom') || 'blank'215 return c.text(message)216 }219- const mHandler = async (c: Context, next: Function) => {217+ const mHandler = async (c: Context, next: Next) => {218 c.req.raw.headers.append('x-custom', 'foo')219 await next()220 }221 222 middleware.push(buildMiddlewareTuple(mHandler))223 middleware.push(buildMiddlewareTuple(handler))224 225 it('Should return 200 Response', async () => {228- const composed = compose<Context>(middleware)226+ const composed = compose(middleware)227 const context = await composed(c)228 expect(context.res).not.toBeNull()229 expect(context.res.status).toBe(200)230 expect(await context.res.text()).toBe('foo')11 unmodified lines242 const handler = () => {243 throw new Error()244 }245 248- const mHandler = async (_c: Context, next: Function) => {246+ const mHandler = async (_c: Context, next: Next) => {247 await next()248 }249 250 middleware.push(buildMiddlewareTuple(mHandler))1 unmodified line252 253 const onNotFound = (c: Context) => c.text('NotFound', 404)254 const onError = (_error: Error, c: Context) => c.text('onError', 500)255 258- const composed = compose<Context>(middleware, onError, onNotFound)256+ const composed = compose(middleware, onError, onNotFound)257 const context = await composed(c)258 expect(context.res).not.toBeNull()259 expect(context.res.status).toBe(500)260 expect(await context.res.text()).toBe('onError')7 unmodified lines268 269 middleware.push(buildMiddlewareTuple(handler))270 const onError = async (_error: Error, c: Context) => c.text('onError', 500)271 274- const composed = compose<Context>(middleware, onError)272+ const composed = compose(middleware, onError)273 const context = await composed(c)274 expect(context.res).not.toBeNull()275 expect(context.res.status).toBe(500)276 expect(await context.res.text()).toBe('onError')277 expect(context.finalized).toBe(true)278 })279 280 it('Run all the middlewares', async () => {283- const ctx: C = { req: {}, res: {}, finalized: false }281 const stack: number[] = []282 const middlewares = [286- async (_ctx: C, next: Function) => {283+ async (_ctx: Context, next: Next) => {284 stack.push(0)285 await next()286 },290- async (_ctx: C, next: Function) => {287+ async (_ctx: Context, next: Next) => {288 stack.push(1)289 await next()290 },294- async (_ctx: C, next: Function) => {291+ async (_ctx: Context, next: Next) => {292 stack.push(2)293 await next()294 },295 ].map((h) => buildMiddlewareTuple(h))296 const composed = compose(middlewares)300- await composed(ctx)297+ await composed(new Context(new Request('http://localhost/')))298 expect(stack).toEqual([0, 1, 2])299 })300 })301 describe('compose with Context - not finalized', () => {4 unmodified lines306 }307 308 it('Should not be finalized - lack `next()`', async () => {309 const middleware: MiddlewareTuple[] = []313- const mHandler = async (_c: Context, next: Function) => {310+ const mHandler = async (_c: Context, next: Next) => {311 await next()312 }313 const mHandler2 = async () => {}314 315 middleware.push(buildMiddlewareTuple(mHandler))316 middleware.push(buildMiddlewareTuple(mHandler2))320- const composed = compose<Context>(middleware, undefined, onNotFound)317+ const composed = compose(middleware, undefined, onNotFound)318 const context = await composed(c)319 expect(context.finalized).toBe(false)320 })321 322 it('Should not be finalized - lack `return Response`', async () => {323 const middleware2: MiddlewareTuple[] = []327- const mHandler3 = async (_c: Context, next: Function) => {324+ const mHandler3 = async (_c: Context, next: Next) => {325 await next()326 }327 const handler = async () => {}328 middleware2.push(buildMiddlewareTuple(mHandler3))329 middleware2.push(buildMiddlewareTuple(handler))330 334- const composed = compose<Context>(middleware2, undefined, onNotFound)331+ const composed = compose(middleware2, undefined, onNotFound)332 const context = await composed(c)333 expect(context.finalized).toBe(false)334 })335 })336+describe('compose with Context - next', () => {337+ const req = new Request('http://localhost/')338+ const c: Context = new Context(req)339 340+ it('Should throw multiple call error', async () => {341+ const middleware: MiddlewareTuple[] = []342+ const mHandler = async (_c: Context, next: Next) => {343+ await next()344+ }345+ const mHandler2 = async (_c: Context, next: Next) => {346+ await next()347+ await next()348+ }349+350+ middleware.push(buildMiddlewareTuple(mHandler))351+ middleware.push(buildMiddlewareTuple(mHandler2))352+353+ const composed = compose(middleware)354+ try {355+ await composed(c)356+ } catch (err) {357+ expect(err).toStrictEqual(new Error('next() called multiple times'))358+ }359+ })360+})361+362 describe('Compose', function () {363 it('should get executed order one by one', async () => {364 const arr: number[] = []365 const stack = []366 const called: boolean[] = []367 368 stack.push(347- buildMiddlewareTuple(async (_context: C, next: Function) => {369+ buildMiddlewareTuple(async (_context: Context, next: Next) => {370 called.push(true)371 372 arr.push(1)373 await next()1 unmodified line375 })376 )377 378 stack.push(357- buildMiddlewareTuple(async (_context: C, next: Function) => {379+ buildMiddlewareTuple(async (_context: Context, next: Next) => {380 called.push(true)381 382 arr.push(2)383 await next()1 unmodified line385 })386 )387 388 stack.push(367- buildMiddlewareTuple(async (_context: C, next: Function) => {389+ buildMiddlewareTuple(async (_context: Context, next: Next) => {390 called.push(true)391 392 arr.push(3)393 await next()394 arr.push(4)395 })396 )397 376- await compose(stack)({ res: null, finalized: false })398+ await compose(stack)(new Context(new Request('http://localhost/')))399 expect(called).toEqual([true, true, true])400 expect(arr).toEqual([1, 2, 3, 4, 5, 6])401 })402 2 unmodified lines405 const stack = []406 const called: boolean[] = []407 408 stack.push(387- buildMiddlewareTuple(async (_context: C, next: Function) => {409+ buildMiddlewareTuple(async (_context: Context, next: Next) => {410 called.push(true)411 412 arr.push(1)413 await next()8 unmodified lines422 })423 )424 425 stack.push(404- buildMiddlewareTuple(async (_context: C, next: Function) => {426+ buildMiddlewareTuple(async (_context: Context, next: Next) => {427 called.push(true)428 429 arr.push(3)430 await next()431 arr.push(4)432 })433 )434 413- await compose(stack)({ res: null, finalized: false })435+ await compose(stack)(new Context(new Request('http://localhost/')))436 expect(called).toEqual([true, true])437 expect(arr).toEqual([1, 2, 6])438 })439 440 it('should be able to be called twice', async () => {419- type C = {420- arr: number[]421- }441 const stack = []442 443 stack.push(425- buildMiddlewareTuple(async (context: C, next: Function) => {426- context.arr.push(1)444+ buildMiddlewareTuple(async (context: Context, next: Next) => {445+ context.get('arr').push(1)446 await next()428- context.arr.push(6)447+ context.get('arr').push(6)448 })449 )450 451 stack.push(433- buildMiddlewareTuple(async (context: C, next: Function) => {434- context.arr.push(2)452+ buildMiddlewareTuple(async (context: Context, next: Next) => {453+ context.get('arr').push(2)454 await next()436- context.arr.push(5)455+ context.get('arr').push(5)456 })457 )458 459 stack.push(441- buildMiddlewareTuple(async (context: C, next: Function) => {442- context.arr.push(3)460+ buildMiddlewareTuple(async (context: Context, next: Next) => {461+ context.get('arr').push(3)462 await next()444- context.arr.push(4)463+ context.get('arr').push(4)464 })465 )466 467 const fn = compose(stack)449- const ctx1 = { arr: [] as number[], res: null, finalized: false }450- const ctx2 = { arr: [] as number[], res: null, finalized: false }468+ const ctx1 = new Context(new Request('http://localhost/'))469+470+ ctx1.set('arr', [])471+472+ const ctx2 = new Context(new Request('http://localhost/'))473+474+ ctx2.set('arr', [])475+476 const out = [1, 2, 3, 4, 5, 6]477 478 await fn(ctx1)479 455- expect(out).toEqual(ctx1.arr)480+ expect(out).toEqual(ctx1.get('arr'))481 await fn(ctx2)482 458- expect(out).toEqual(ctx2.arr)483+ expect(out).toEqual(ctx2.get('arr'))484 })485 486 it('should create next functions that return a Promise', async () => {487 const stack = []488 const arr: unknown[] = []489 for (let i = 0; i < 5; i++) {490 stack.push(466- buildMiddlewareTuple((_context: C, next: Function) => {491+ buildMiddlewareTuple((_context: Context, next: Next) => {492 arr.push(next())493 })494 )495 }496 472- await compose(stack)({ res: null, finalized: false })497+ await compose(stack)(new Context(new Request('http://localhost/')))498 499 for (const next of arr) {500 const isPromise = !!(next as { then?: Function })?.then501 expect(isPromise).toBe(true)502 }503 })504 505 it('should work with 0 middleware', async () => {481- await compose([])({ res: null, finalized: false })506+ await compose([])(new Context(new Request('http://localhost/')))507 })508 509 it('should work when yielding at the end of the stack', async () => {510 const stack = []511 let called = false512 513 stack.push(489- buildMiddlewareTuple(async (_ctx: C, next: Function) => {514+ buildMiddlewareTuple(async (_ctx: Context, next: Next) => {515 await next()516 called = true517 })518 )519 495- await compose(stack)({ res: null, finalized: false })520+ await compose(stack)(new Context(new Request('http://localhost/')))521 expect(called).toBe(true)522 })523 524 it('should reject on errors in middleware', async () => {5 unmodified lines530 })531 )532 533 try {509- await compose(stack)({ res: null, finalized: false })534+ await compose(stack)(new Context(new Request('http://localhost/')))535 throw new Error('promise was not rejected')536 } catch (e) {537 expect(e).toBeInstanceOf(ExpectedError)538 }539 })540 541 it('should keep the context', async () => {517- const ctx = { res: null, finalized: false }542+ const ctx = new Context(new Request('http://localhost/'))543 544 const stack = []545 546 stack.push(522- buildMiddlewareTuple(async (ctx2: C, next: Function) => {547+ buildMiddlewareTuple(async (ctx2: Context, next: Next) => {548 await next()549 expect(ctx2).toEqual(ctx)550 })551 )552 553 stack.push(529- buildMiddlewareTuple(async (ctx2: C, next: Function) => {554+ buildMiddlewareTuple(async (ctx2: Context, next: Next) => {555 await next()556 expect(ctx2).toEqual(ctx)557 })558 )559 560 stack.push(536- buildMiddlewareTuple(async (ctx2: C, next: Function) => {561+ buildMiddlewareTuple(async (ctx2: Context, next: Next) => {562 await next()563 expect(ctx2).toEqual(ctx)564 })565 )5 unmodified lines571 const arr: number[] = []572 const stack = []573 574 stack.push(550- buildMiddlewareTuple(async (_ctx: C, next: Function) => {575+ buildMiddlewareTuple(async (_ctx: Context, next: Next) => {576 arr.push(1)577 try {578 arr.push(6)579 await next()11 unmodified lines591 throw new Error()592 })593 )594 570- await compose(stack)({ res: null, finalized: false })595+ await compose(stack)(new Context(new Request('http://localhost/')))596 expect(arr).toEqual([1, 6, 4, 2, 3])597 })598 599 it('should compose w/ next', async () => {600 let called = false601 577- await compose([])({ res: null, finalized: false }, async () => {602+ await compose([])(new Context(new Request('http://localhost/')), async () => {603 called = true604 })605 expect(called).toBe(true)606 })7 unmodified lines614 })615 )616 617 try {593- await compose(stack)({ res: null, finalized: false })618+ await compose(stack)(new Context(new Request('http://localhost/')))619 throw new Error('promise was not rejected')620 } catch (e) {621 expect(e).toBeInstanceOf(ExpectedError)622 }5 unmodified lines628 629 await compose([630 buildMiddlewareTuple(631 compose([607- buildMiddlewareTuple((_ctx: C, next: Function) => {632+ buildMiddlewareTuple((_ctx: Context, next: Next) => {633 called.push(1)634 return next()635 }),611- buildMiddlewareTuple((_ctx: C, next: Function) => {636+ buildMiddlewareTuple((_ctx: Context, next: Next) => {637 called.push(2)638 return next()639 }),640 ])641 ),617- buildMiddlewareTuple((_ctx: C, next: Function) => {642+ buildMiddlewareTuple((_ctx: Context, next: Next) => {643 called.push(3)644 return next()645 }),621- ])({ res: null, finalized: false })646+ ])(new Context(new Request('http://localhost/')))647 648 expect(called).toEqual([1, 2, 3])649 })650 651 it('should throw if next() is called multiple times', async () => {652 try {653 await compose([629- buildMiddlewareTuple(async (_ctx: C, next: Function) => {654+ buildMiddlewareTuple(async (_ctx: Context, next: Next) => {655 await next()656 await next()657 }),633- ])({ res: null, finalized: false })658+ ])(new Context(new Request('http://localhost/')))659 throw new Error('boom')660 } catch (err) {661 expect(err instanceof Error && /multiple times/.test(err.message)).toBe(true)662 }3 unmodified lines666 let val = 0667 await compose([668 buildMiddlewareTuple(669 compose([645- buildMiddlewareTuple((_ctx: C, next: Function) => {670+ buildMiddlewareTuple((_ctx: Context, next: Next) => {671 val++672 return next()673 }),649- buildMiddlewareTuple((_ctx: C, next: Function) => {674+ buildMiddlewareTuple((_ctx: Context, next: Next) => {675 val++676 return next()677 }),678 ])679 ),655- buildMiddlewareTuple((_ctx: C, next: Function) => {680+ buildMiddlewareTuple((_ctx: Context, next: Next) => {681 val++682 return next()683 }),659- ])({ res: null, finalized: false })684+ ])(new Context(new Request('http://localhost/')))685 686 expect(val).toEqual(3)687 })688 689 it('should return last return value', async () => {665- type C = {666- val: number667- finalized: boolean668- res: unknown669- }690 const stack = []691 692 stack.push(673- buildMiddlewareTuple(async (ctx: C, next: Function) => {693+ buildMiddlewareTuple(async (ctx: Context, next: Next) => {694 await next()675- expect(ctx.val).toEqual(2)676- ctx.val = 1695+ expect(ctx.get('val')).toEqual(2)696+ ctx.set('val', 1)697 })698 )699 700 stack.push(681- buildMiddlewareTuple(async (ctx: C, next: Function) => {682- ctx.val = 2701+ buildMiddlewareTuple(async (ctx: Context, next: Next) => {702+ ctx.set('val', 2)703 await next()684- expect(ctx.val).toEqual(2)704+ expect(ctx.get('val')).toEqual(2)705 })706 )707 688- const res = await compose<C>(stack)({ val: 0, res: null, finalized: false })689- expect(res.val).toEqual(1)708+ const res = await compose(stack)(new Context(new Request('http://localhost/')))709+ expect(res.get('val')).toEqual(1)710 })711 712 it('should not affect the original middleware array', () => {713 const middleware: MiddlewareTuple[] = []694- const fn1 = (_ctx: C, next: Function) => {714+ const fn1 = (_ctx: Context, next: Next) => {715 return next()716 }717 middleware.push(buildMiddlewareTuple(fn1))718 8 unmodified lines727 }728 })729 730 it('should not get stuck on the passed in next', async () => {711- type C = {712- middleware: number713- next: number714- finalized: boolean715- res: unknown716- }717-731 const middleware = [719- buildMiddlewareTuple((ctx: C, next: Function) => {720- ctx.middleware++732+ buildMiddlewareTuple((ctx: Context, next: Next) => {733+ ctx.set('middleware', ctx.get('middleware') + 1)734 return next()735 }),736 ]724- const ctx = {725- middleware: 0,726- next: 0,727- finalized: false,728- res: null,729- }737 731- await compose<C>(middleware)(ctx, (ctx: C, next: Function) => {732- ctx.next++738+ const ctx = new Context(new Request('http://localhost/'))739+740+ ctx.set('middleware', 0)741+ ctx.set('next', 0)742+743+ await compose(middleware)(ctx, (ctx: Context, next: Next) => {744+ ctx.set('next', ctx.get('next') + 1)745 return next()746 })747 736- expect(ctx.middleware).toEqual(1)737- expect(ctx.next).toEqual(1)748+ expect(ctx.get('middleware')).toEqual(1)749+ expect(ctx.get('next')).toEqual(1)750 })751 })modified:src/compose.ts+14 added-36 removed
1-import { Context } from './context'1+import type { Context } from './context'2 import type { Env, ErrorHandler, NotFoundHandler } from './types'3 4 /**5- * Interface representing the context for a composition operation.6- */7-interface ComposeContext {8- /**9- * Indicates whether the composition process has been finalized.10- */11- finalized: boolean12-13- /**14- * The result of the composition process. The type is unknown and should be15- * specified based on the context where this interface is used.16- */17- res: unknown18-}19-20-/**5 * Compose middleware functions into a single function based on `koa-compose` package.6 *23- * @template C - The context type.7 * @template E - The environment type.8 *9 * @param {[[Function, unknown], ParamIndexMap | Params][]} middleware - An array of middleware functions and their corresponding parameters.10 * @param {ErrorHandler<E>} [onError] - An optional error handler function.11 * @param {NotFoundHandler<E>} [onNotFound] - An optional not-found handler function.12 *30- * @returns {(context: C, next?: Function) => Promise<C>} - A composed middleware function.13+ * @returns {(context: Context, next?: Function) => Promise<>} - A composed middleware function.14 */32-export const compose = <C extends ComposeContext, E extends Env = Env>(15+export const compose = <E extends Env = Env>(16 middleware: [[Function, unknown], unknown][] | [[Function]][],17 onError?: ErrorHandler<E>,18 onNotFound?: NotFoundHandler<E>36-): ((context: C, next?: Function) => Promise<C>) => {19+): ((context: Context, next?: Function) => Promise<Context>) => {20 return (context, next) => {21 let index = -139- const isContext = context instanceof Context22 23 return dispatch(0)24 25 /**26 * Dispatch the middleware functions.27 *28 * @param {number} i - The current index in the middleware array.29 *48- * @returns {Promise<C>} - A promise that resolves to the context.30+ * @returns {Promise<Context>} - A promise that resolves to the context.31 */50- async function dispatch(i: number): Promise<C> {32+ async function dispatch(i: number): Promise<Context> {33 if (i <= index) {34 throw new Error('next() called multiple times')35 }36 index = i3 unmodified lines40 let handler41 42 if (middleware[i]) {43 handler = middleware[i][0][0]62- if (isContext) {63- context.req.routeIndex = i44+ context.req.routeIndex = i64- }45 } else {46 handler = (i === middleware.length && next) || undefined47 }48 69- if (!handler) {70- if (isContext && context.finalized === false && onNotFound) {71- res = await onNotFound(context)72- }73- } else {49+ if (handler) {50 try {75- res = await handler(context, () => {76- return dispatch(i + 1)77- })51+ res = await handler(context, () => dispatch(i + 1))52 } catch (err) {79- if (err instanceof Error && isContext && onError) {53+ if (err instanceof Error && onError) {54 context.error = err55 res = await onError(err, context)56 isError = true57 } else {58 throw err59 }60 }61+ } else {62+ if (context.finalized === false && onNotFound) {63+ res = await onNotFound(context)64+ }65 }66 67 if (res && (context.finalized === false || isError)) {68 context.res = res5 unmodified linesmodified:src/hono-base.ts+2 added-2 removed
213 unmodified lines214 if (app.errorHandler === errorHandler) {215 handler = r.handler216 } else {217 handler = async (c: Context, next: Next) =>218- (await compose<Context>([], app.errorHandler)(c, () => r.handler(c, next))).res218+ (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res219 ;(handler as any)[COMPOSED_HANDLER] = r.handler220 }221 222 subApp.#addRoute(r.method, r.path, handler)204 unmodified lines427 .catch((err: Error) => this.#handleError(err, c))428 : res ?? this.#notFoundHandler(c)429 }430 431- const composed = compose<Context>(matchResult[0], this.errorHandler, this.#notFoundHandler)431+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler)432 433 return (async () => {434 try {435 const context = await composed(c)81 unmodified lines