Skip to content
Myr

compose.test.ts

This file

Path

src/compose.test.ts

740 lines 路 19.1 KiB 路 TypeScript

Last changed by

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

History of this file

Take it

1import { compose } from './compose'2import { Context } from './context'3import { HonoRequest } from './request'4import type { Params } from './router'56type C = {7  req: Record<string, string>8  res: Record<string, string>9  finalized: boolean10}1112type MiddlewareTuple = [[Function, unknown], Params]1314class ExpectedError extends Error {}1516function buildMiddlewareTuple(fn: Function, params?: Params): MiddlewareTuple {17  return [[fn, undefined], params || {}]18}1920describe('compose', () => {21  const middleware: MiddlewareTuple[] = []2223  const a = async (c: C, next: Function) => {24    c.req['log'] = 'log'25    await next()26  }2728  const b = async (c: C, next: Function) => {29    await next()30    c.res['headers'] = 'custom-header'31  }3233  const c = async (c: C, next: Function) => {34    c.req['xxx'] = 'yyy'35    await next()36    c.res['zzz'] = c.req['xxx']37  }3839  const handler = async (c: C, next: Function) => {40    c.req['log'] = `${c.req.log} message`41    await next()42    c.res = { message: 'new response' }43  }4445  middleware.push(buildMiddlewareTuple(a))46  middleware.push(buildMiddlewareTuple(b))47  middleware.push(buildMiddlewareTuple(c))48  middleware.push(buildMiddlewareTuple(handler))4950  it('Request', async () => {51    const c: C = { req: {}, res: {}, finalized: false }52    const composed = compose<C>(middleware)53    const context = await composed(c)54    expect(context.req['log']).not.toBeNull()55    expect(context.req['log']).toBe('log message')56    expect(context.req['xxx']).toBe('yyy')57  })58  it('Response', async () => {59    const c: C = { req: {}, res: {}, finalized: false }60    const composed = compose<C>(middleware)61    const context = await composed(c)62    expect(context.res['headers']).not.toBeNull()63    expect(context.res['headers']).toBe('custom-header')64    expect(context.res['message']).toBe('new response')65    expect(context.res['zzz']).toBe('yyy')66  })67})6869describe('compose with returning a promise, non-async function', () => {70  const handlers: MiddlewareTuple[] = [71    buildMiddlewareTuple(() => {72      return new Promise((resolve) =>73        setTimeout(() => {74          resolve({ message: 'new response' })75        }, 1)76      )77    }),78  ]7980  it('Response', async () => {81    const c: C = { req: {}, res: {}, finalized: false }82    const composed = compose<C>(handlers)83    const context = await composed(c)84    expect(context.res['message']).toBe('new response')85  })86})8788describe('Handler and middlewares', () => {89  const middleware: MiddlewareTuple[] = []9091  const req = new HonoRequest(new Request('http://localhost/'))92  const c: Context = new Context(req)9394  const mHandlerFoo = async (c: Context, next: Function) => {95    c.req.raw.headers.append('x-header-foo', 'foo')96    await next()97  }9899  const mHandlerBar = async (c: Context, next: Function) => {100    await next()101    c.header('x-header-bar', 'bar')102  }103104  const handler = (c: Context) => {105    const foo = c.req.header('x-header-foo') || ''106    return c.text(foo)107  }108109  middleware.push(buildMiddlewareTuple(mHandlerFoo))110  middleware.push(buildMiddlewareTuple(mHandlerBar))111  middleware.push(buildMiddlewareTuple(handler))112113  it('Should return 200 Response', async () => {114    const composed = compose<Context>(middleware)115    const context = await composed(c)116    const res = context.res117    expect(res).not.toBeNull()118    expect(res.status).toBe(200)119    expect(await res.text()).toBe('foo')120    expect(res.headers.get('x-header-bar')).toBe('bar')121  })122})123124describe('compose with Context - 200 success', () => {125  const middleware: MiddlewareTuple[] = []126127  const req = new HonoRequest(new Request('http://localhost/'))128  const c: Context = new Context(req)129  const handler = (c: Context) => {130    return c.text('Hello')131  }132  const mHandler = async (_c: Context, next: Function) => {133    await next()134  }135136  middleware.push(buildMiddlewareTuple(handler))137  middleware.push(buildMiddlewareTuple(mHandler))138139  it('Should return 200 Response', async () => {140    const composed = compose<Context>(middleware)141    const context = await composed(c)142    expect(context.res).not.toBeNull()143    expect(context.res.status).toBe(200)144    expect(await context.res.text()).toBe('Hello')145  })146})147148describe('compose with Context - 404 not found', () => {149  const middleware: MiddlewareTuple[] = []150151  const req = new HonoRequest(new Request('http://localhost/'))152  const onNotFound = (c: Context) => {153    return c.text('onNotFound', 404)154  }155  const onNotFoundAsync = async (c: Context) => {156    return c.text('onNotFoundAsync', 404)157  }158  const mHandler = async (_c: Context, next: Function) => {159    await next()160  }161162  middleware.push(buildMiddlewareTuple(mHandler))163164  it('Should return 404 Response', async () => {165    const c: Context = new Context(req)166    const composed = compose<Context>(middleware, undefined, onNotFound)167    const context = await composed(c)168    expect(context.res).not.toBeNull()169    expect(context.res.status).toBe(404)170    expect(await context.res.text()).toBe('onNotFound')171    expect(context.finalized).toBe(true)172  })173174  it('Should return 404 Response - async handler', async () => {175    const c: Context = new Context(req)176    const composed = compose<Context>(middleware, undefined, onNotFoundAsync)177    const context = await composed(c)178    expect(context.res).not.toBeNull()179    expect(context.res.status).toBe(404)180    expect(await context.res.text()).toBe('onNotFoundAsync')181    expect(context.finalized).toBe(true)182  })183})184185describe('compose with Context - 401 not authorized', () => {186  const middleware: MiddlewareTuple[] = []187188  const req = new HonoRequest(new Request('http://localhost/'))189  const c: Context = new Context(req)190  const handler = (c: Context) => {191    return c.text('Hello')192  }193  const mHandler = async (c: Context, next: Function) => {194    await next()195    c.res = new Response('Not authorized', { status: 401 })196  }197198  middleware.push(buildMiddlewareTuple(mHandler))199  middleware.push(buildMiddlewareTuple(handler))200201  it('Should return 401 Response', async () => {202    const composed = compose<Context>(middleware)203    const context = await composed(c)204    expect(context.res).not.toBeNull()205    expect(context.res.status).toBe(401)206    expect(await context.res.text()).toBe('Not authorized')207    expect(context.finalized).toBe(true)208  })209})210211describe('compose with Context - next() below', () => {212  const middleware: MiddlewareTuple[] = []213214  const req = new HonoRequest(new Request('http://localhost/'))215  const c: Context = new Context(req)216  const handler = (c: Context) => {217    const message = c.req.header('x-custom') || 'blank'218    return c.text(message)219  }220  const mHandler = async (c: Context, next: Function) => {221    c.req.raw.headers.append('x-custom', 'foo')222    await next()223  }224225  middleware.push(buildMiddlewareTuple(mHandler))226  middleware.push(buildMiddlewareTuple(handler))227228  it('Should return 200 Response', async () => {229    const composed = compose<Context>(middleware)230    const context = await composed(c)231    expect(context.res).not.toBeNull()232    expect(context.res.status).toBe(200)233    expect(await context.res.text()).toBe('foo')234    expect(context.finalized).toBe(true)235  })236})237238describe('compose with Context - 500 error', () => {239  const middleware: MiddlewareTuple[] = []240241  const req = new HonoRequest(new Request('http://localhost/'))242  const c: Context = new Context(req)243244  it('Error on handler', async () => {245    const handler = () => {246      throw new Error()247    }248249    const mHandler = async (_c: Context, next: Function) => {250      await next()251    }252253    middleware.push(buildMiddlewareTuple(mHandler))254    middleware.push(buildMiddlewareTuple(handler))255256    const onNotFound = (c: Context) => c.text('NotFound', 404)257    const onError = (_error: Error, c: Context) => c.text('onError', 500)258259    const composed = compose<Context>(middleware, onError, onNotFound)260    const context = await composed(c)261    expect(context.res).not.toBeNull()262    expect(context.res.status).toBe(500)263    expect(await context.res.text()).toBe('onError')264    expect(context.finalized).toBe(true)265  })266267  it('Error on handler - async', async () => {268    const handler = () => {269      throw new Error()270    }271272    middleware.push(buildMiddlewareTuple(handler))273    const onError = async (_error: Error, c: Context) => c.text('onError', 500)274275    const composed = compose<Context>(middleware, onError)276    const context = await composed(c)277    expect(context.res).not.toBeNull()278    expect(context.res.status).toBe(500)279    expect(await context.res.text()).toBe('onError')280    expect(context.finalized).toBe(true)281  })282283  it('Run all the middlewares', async () => {284    const ctx: C = { req: {}, res: {}, finalized: false }285    const stack: number[] = []286    const middlewares = [287      async (_ctx: C, next: Function) => {288        stack.push(0)289        await next()290      },291      async (_ctx: C, next: Function) => {292        stack.push(1)293        await next()294      },295      async (_ctx: C, next: Function) => {296        stack.push(2)297        await next()298      },299    ].map((h) => buildMiddlewareTuple(h))300    const composed = compose(middlewares)301    await composed(ctx)302    expect(stack).toEqual([0, 1, 2])303  })304})305describe('compose with Context - not finalized', () => {306  const req = new HonoRequest(new Request('http://localhost/'))307  const c: Context = new Context(req)308  const onNotFound = (c: Context) => {309    return c.text('onNotFound', 404)310  }311312  it('Should not be finalized - lack `next()`', async () => {313    const middleware: MiddlewareTuple[] = []314    const mHandler = async (_c: Context, next: Function) => {315      await next()316    }317    const mHandler2 = async () => {}318319    middleware.push(buildMiddlewareTuple(mHandler))320    middleware.push(buildMiddlewareTuple(mHandler2))321    const composed = compose<Context>(middleware, undefined, onNotFound)322    const context = await composed(c)323    expect(context.finalized).toBe(false)324  })325326  it('Should not be finalized - lack `return Response`', async () => {327    const middleware2: MiddlewareTuple[] = []328    const mHandler3 = async (_c: Context, next: Function) => {329      await next()330    }331    const handler = async () => {}332    middleware2.push(buildMiddlewareTuple(mHandler3))333    middleware2.push(buildMiddlewareTuple(handler))334335    const composed = compose<Context>(middleware2, undefined, onNotFound)336    const context = await composed(c)337    expect(context.finalized).toBe(false)338  })339})340341describe('Compose', function () {342  it('should get executed order one by one', async () => {343    const arr: number[] = []344    const stack = []345    const called: boolean[] = []346347    stack.push(348      buildMiddlewareTuple(async (_context: C, next: Function) => {349        called.push(true)350351        arr.push(1)352        await next()353        arr.push(6)354      })355    )356357    stack.push(358      buildMiddlewareTuple(async (_context: C, next: Function) => {359        called.push(true)360361        arr.push(2)362        await next()363        arr.push(5)364      })365    )366367    stack.push(368      buildMiddlewareTuple(async (_context: C, next: Function) => {369        called.push(true)370371        arr.push(3)372        await next()373        arr.push(4)374      })375    )376377    await compose(stack)({ res: null, finalized: false })378    expect(called).toEqual([true, true, true])379    expect(arr).toEqual([1, 2, 3, 4, 5, 6])380  })381382  it('should not get executed if previous next() not triggered', async () => {383    const arr: number[] = []384    const stack = []385    const called: boolean[] = []386387    stack.push(388      buildMiddlewareTuple(async (_context: C, next: Function) => {389        called.push(true)390391        arr.push(1)392        await next()393        arr.push(6)394      })395    )396397    stack.push(398      buildMiddlewareTuple(async () => {399        called.push(true)400        arr.push(2)401      })402    )403404    stack.push(405      buildMiddlewareTuple(async (_context: C, next: Function) => {406        called.push(true)407408        arr.push(3)409        await next()410        arr.push(4)411      })412    )413414    await compose(stack)({ res: null, finalized: false })415    expect(called).toEqual([true, true])416    expect(arr).toEqual([1, 2, 6])417  })418419  it('should be able to be called twice', async () => {420    type C = {421      arr: number[]422    }423    const stack = []424425    stack.push(426      buildMiddlewareTuple(async (context: C, next: Function) => {427        context.arr.push(1)428        await next()429        context.arr.push(6)430      })431    )432433    stack.push(434      buildMiddlewareTuple(async (context: C, next: Function) => {435        context.arr.push(2)436        await next()437        context.arr.push(5)438      })439    )440441    stack.push(442      buildMiddlewareTuple(async (context: C, next: Function) => {443        context.arr.push(3)444        await next()445        context.arr.push(4)446      })447    )448449    const fn = compose(stack)450    const ctx1 = { arr: [] as number[], res: null, finalized: false }451    const ctx2 = { arr: [] as number[], res: null, finalized: false }452    const out = [1, 2, 3, 4, 5, 6]453454    await fn(ctx1)455456    expect(out).toEqual(ctx1.arr)457    await fn(ctx2)458459    expect(out).toEqual(ctx2.arr)460  })461462  it('should create next functions that return a Promise', async () => {463    const stack = []464    const arr: unknown[] = []465    for (let i = 0; i < 5; i++) {466      stack.push(467        buildMiddlewareTuple((_context: C, next: Function) => {468          arr.push(next())469        })470      )471    }472473    await compose(stack)({ res: null, finalized: false })474475    for (const next of arr) {476      const isPromise = !!(next as { then?: Function })?.then477      expect(isPromise).toBe(true)478    }479  })480481  it('should work with 0 middleware', async () => {482    await compose([])({ res: null, finalized: false })483  })484485  it('should work when yielding at the end of the stack', async () => {486    const stack = []487    let called = false488489    stack.push(490      buildMiddlewareTuple(async (_ctx: C, next: Function) => {491        await next()492        called = true493      })494    )495496    await compose(stack)({ res: null, finalized: false })497    expect(called).toBe(true)498  })499500  it('should reject on errors in middleware', async () => {501    const stack = []502503    stack.push(504      buildMiddlewareTuple(() => {505        throw new ExpectedError()506      })507    )508509    try {510      await compose(stack)({ res: null, finalized: false })511      throw new Error('promise was not rejected')512    } catch (e) {513      expect(e).toBeInstanceOf(ExpectedError)514    }515  })516517  it('should keep the context', async () => {518    const ctx = { res: null, finalized: false }519520    const stack = []521522    stack.push(523      buildMiddlewareTuple(async (ctx2: C, next: Function) => {524        await next()525        expect(ctx2).toEqual(ctx)526      })527    )528529    stack.push(530      buildMiddlewareTuple(async (ctx2: C, next: Function) => {531        await next()532        expect(ctx2).toEqual(ctx)533      })534    )535536    stack.push(537      buildMiddlewareTuple(async (ctx2: C, next: Function) => {538        await next()539        expect(ctx2).toEqual(ctx)540      })541    )542543    await compose(stack)(ctx)544  })545546  it('should catch downstream errors', async () => {547    const arr: number[] = []548    const stack = []549550    stack.push(551      buildMiddlewareTuple(async (_ctx: C, next: Function) => {552        arr.push(1)553        try {554          arr.push(6)555          await next()556          arr.push(7)557        } catch (err) {558          arr.push(2)559        }560        arr.push(3)561      })562    )563564    stack.push(565      buildMiddlewareTuple(async () => {566        arr.push(4)567        throw new Error()568      })569    )570571    await compose(stack)({ res: null, finalized: false })572    expect(arr).toEqual([1, 6, 4, 2, 3])573  })574575  it('should compose w/ next', async () => {576    let called = false577578    await compose([])({ res: null, finalized: false }, async () => {579      called = true580    })581    expect(called).toBe(true)582  })583584  it('should handle errors in wrapped non-async functions', async () => {585    const stack = []586587    stack.push(588      buildMiddlewareTuple(function () {589        throw new ExpectedError()590      })591    )592593    try {594      await compose(stack)({ res: null, finalized: false })595      throw new Error('promise was not rejected')596    } catch (e) {597      expect(e).toBeInstanceOf(ExpectedError)598    }599  })600601  // https://github.com/koajs/compose/pull/27#issuecomment-143109739602  it('should compose w/ other compositions', async () => {603    const called: number[] = []604605    await compose([606      buildMiddlewareTuple(607        compose([608          buildMiddlewareTuple((_ctx: C, next: Function) => {609            called.push(1)610            return next()611          }),612          buildMiddlewareTuple((_ctx: C, next: Function) => {613            called.push(2)614            return next()615          }),616        ])617      ),618      buildMiddlewareTuple((_ctx: C, next: Function) => {619        called.push(3)620        return next()621      }),622    ])({ res: null, finalized: false })623624    expect(called).toEqual([1, 2, 3])625  })626627  it('should throw if next() is called multiple times', async () => {628    try {629      await compose([630        buildMiddlewareTuple(async (_ctx: C, next: Function) => {631          await next()632          await next()633        }),634      ])({ res: null, finalized: false })635      throw new Error('boom')636    } catch (err) {637      expect(err instanceof Error && /multiple times/.test(err.message)).toBe(true)638    }639  })640641  it('should return a valid middleware', async () => {642    let val = 0643    await compose([644      buildMiddlewareTuple(645        compose([646          buildMiddlewareTuple((_ctx: C, next: Function) => {647            val++648            return next()649          }),650          buildMiddlewareTuple((_ctx: C, next: Function) => {651            val++652            return next()653          }),654        ])655      ),656      buildMiddlewareTuple((_ctx: C, next: Function) => {657        val++658        return next()659      }),660    ])({ res: null, finalized: false })661662    expect(val).toEqual(3)663  })664665  it('should return last return value', async () => {666    type C = {667      val: number668      finalized: boolean669      res: unknown670    }671    const stack = []672673    stack.push(674      buildMiddlewareTuple(async (ctx: C, next: Function) => {675        await next()676        expect(ctx.val).toEqual(2)677        ctx.val = 1678      })679    )680681    stack.push(682      buildMiddlewareTuple(async (ctx: C, next: Function) => {683        ctx.val = 2684        await next()685        expect(ctx.val).toEqual(2)686      })687    )688689    const res = await compose<C>(stack)({ val: 0, res: null, finalized: false })690    expect(res.val).toEqual(1)691  })692693  it('should not affect the original middleware array', () => {694    const middleware: MiddlewareTuple[] = []695    const fn1 = (_ctx: C, next: Function) => {696      return next()697    }698    middleware.push(buildMiddlewareTuple(fn1))699700    for (const [[fn]] of middleware) {701      expect(fn).toEqual(fn1)702    }703704    compose(middleware)705706    for (const [[fn]] of middleware) {707      expect(fn).toEqual(fn1)708    }709  })710711  it('should not get stuck on the passed in next', async () => {712    type C = {713      middleware: number714      next: number715      finalized: boolean716      res: unknown717    }718719    const middleware = [720      buildMiddlewareTuple((ctx: C, next: Function) => {721        ctx.middleware++722        return next()723      }),724    ]725    const ctx = {726      middleware: 0,727      next: 0,728      finalized: false,729      res: null,730    }731732    await compose<C>(middleware)(ctx, (ctx: C, next: Function) => {733      ctx.next++734      return next()735    })736737    expect(ctx.middleware).toEqual(1)738    expect(ctx.next).toEqual(1)739  })740})