Skip to content
Myr

compose.test.ts

This file

Path

src/compose.test.ts

739 lines 路 19.0 KiB 路 TypeScript

Last changed by

chore(lint): ESLint v9 (#3393)Yusuke Wadabefore adoption5f78e4e

History of this file

Take it

1import { compose } from './compose'2import { Context } from './context'3import type { Params } from './router'45type C = {6  req: Record<string, string>7  res: Record<string, string>8  finalized: boolean9}1011type MiddlewareTuple = [[Function, unknown], Params]1213class ExpectedError extends Error {}1415function buildMiddlewareTuple(fn: Function, params?: Params): MiddlewareTuple {16  return [[fn, undefined], params || {}]17}1819describe('compose', () => {20  const middleware: MiddlewareTuple[] = []2122  const a = async (c: C, next: Function) => {23    c.req['log'] = 'log'24    await next()25  }2627  const b = async (c: C, next: Function) => {28    await next()29    c.res['headers'] = 'custom-header'30  }3132  const c = async (c: C, next: Function) => {33    c.req['xxx'] = 'yyy'34    await next()35    c.res['zzz'] = c.req['xxx']36  }3738  const handler = async (c: C, next: Function) => {39    c.req['log'] = `${c.req.log} message`40    await next()41    c.res = { message: 'new response' }42  }4344  middleware.push(buildMiddlewareTuple(a))45  middleware.push(buildMiddlewareTuple(b))46  middleware.push(buildMiddlewareTuple(c))47  middleware.push(buildMiddlewareTuple(handler))4849  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')56  })57  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')65  })66})6768describe('compose with returning a promise, non-async function', () => {69  const handlers: MiddlewareTuple[] = [70    buildMiddlewareTuple(() => {71      return new Promise((resolve) =>72        setTimeout(() => {73          resolve({ message: 'new response' })74        }, 1)75      )76    }),77  ]7879  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')84  })85})8687describe('Handler and middlewares', () => {88  const middleware: MiddlewareTuple[] = []8990  const req = new Request('http://localhost/')91  const c: Context = new Context(req)9293  const mHandlerFoo = async (c: Context, next: Function) => {94    c.req.raw.headers.append('x-header-foo', 'foo')95    await next()96  }9798  const mHandlerBar = async (c: Context, next: Function) => {99    await next()100    c.header('x-header-bar', 'bar')101  }102103  const handler = (c: Context) => {104    const foo = c.req.header('x-header-foo') || ''105    return c.text(foo)106  }107108  middleware.push(buildMiddlewareTuple(mHandlerFoo))109  middleware.push(buildMiddlewareTuple(mHandlerBar))110  middleware.push(buildMiddlewareTuple(handler))111112  it('Should return 200 Response', async () => {113    const composed = compose<Context>(middleware)114    const context = await composed(c)115    const res = context.res116    expect(res).not.toBeNull()117    expect(res.status).toBe(200)118    expect(await res.text()).toBe('foo')119    expect(res.headers.get('x-header-bar')).toBe('bar')120  })121})122123describe('compose with Context - 200 success', () => {124  const middleware: MiddlewareTuple[] = []125126  const req = new Request('http://localhost/')127  const c: Context = new Context(req)128  const handler = (c: Context) => {129    return c.text('Hello')130  }131  const mHandler = async (_c: Context, next: Function) => {132    await next()133  }134135  middleware.push(buildMiddlewareTuple(handler))136  middleware.push(buildMiddlewareTuple(mHandler))137138  it('Should return 200 Response', async () => {139    const composed = compose<Context>(middleware)140    const context = await composed(c)141    expect(context.res).not.toBeNull()142    expect(context.res.status).toBe(200)143    expect(await context.res.text()).toBe('Hello')144  })145})146147describe('compose with Context - 404 not found', () => {148  const middleware: MiddlewareTuple[] = []149150  const req = new Request('http://localhost/')151  const onNotFound = (c: Context) => {152    return c.text('onNotFound', 404)153  }154  const onNotFoundAsync = async (c: Context) => {155    return c.text('onNotFoundAsync', 404)156  }157  const mHandler = async (_c: Context, next: Function) => {158    await next()159  }160161  middleware.push(buildMiddlewareTuple(mHandler))162163  it('Should return 404 Response', async () => {164    const c: Context = new Context(req)165    const composed = compose<Context>(middleware, undefined, onNotFound)166    const context = await composed(c)167    expect(context.res).not.toBeNull()168    expect(context.res.status).toBe(404)169    expect(await context.res.text()).toBe('onNotFound')170    expect(context.finalized).toBe(true)171  })172173  it('Should return 404 Response - async handler', async () => {174    const c: Context = new Context(req)175    const composed = compose<Context>(middleware, undefined, onNotFoundAsync)176    const context = await composed(c)177    expect(context.res).not.toBeNull()178    expect(context.res.status).toBe(404)179    expect(await context.res.text()).toBe('onNotFoundAsync')180    expect(context.finalized).toBe(true)181  })182})183184describe('compose with Context - 401 not authorized', () => {185  const middleware: MiddlewareTuple[] = []186187  const req = new Request('http://localhost/')188  const c: Context = new Context(req)189  const handler = (c: Context) => {190    return c.text('Hello')191  }192  const mHandler = async (c: Context, next: Function) => {193    await next()194    c.res = new Response('Not authorized', { status: 401 })195  }196197  middleware.push(buildMiddlewareTuple(mHandler))198  middleware.push(buildMiddlewareTuple(handler))199200  it('Should return 401 Response', async () => {201    const composed = compose<Context>(middleware)202    const context = await composed(c)203    expect(context.res).not.toBeNull()204    expect(context.res.status).toBe(401)205    expect(await context.res.text()).toBe('Not authorized')206    expect(context.finalized).toBe(true)207  })208})209210describe('compose with Context - next() below', () => {211  const middleware: MiddlewareTuple[] = []212213  const req = new Request('http://localhost/')214  const c: Context = new Context(req)215  const handler = (c: Context) => {216    const message = c.req.header('x-custom') || 'blank'217    return c.text(message)218  }219  const mHandler = async (c: Context, next: Function) => {220    c.req.raw.headers.append('x-custom', 'foo')221    await next()222  }223224  middleware.push(buildMiddlewareTuple(mHandler))225  middleware.push(buildMiddlewareTuple(handler))226227  it('Should return 200 Response', async () => {228    const composed = compose<Context>(middleware)229    const context = await composed(c)230    expect(context.res).not.toBeNull()231    expect(context.res.status).toBe(200)232    expect(await context.res.text()).toBe('foo')233    expect(context.finalized).toBe(true)234  })235})236237describe('compose with Context - 500 error', () => {238  const middleware: MiddlewareTuple[] = []239240  const req = new Request('http://localhost/')241  const c: Context = new Context(req)242243  it('Error on handler', async () => {244    const handler = () => {245      throw new Error()246    }247248    const mHandler = async (_c: Context, next: Function) => {249      await next()250    }251252    middleware.push(buildMiddlewareTuple(mHandler))253    middleware.push(buildMiddlewareTuple(handler))254255    const onNotFound = (c: Context) => c.text('NotFound', 404)256    const onError = (_error: Error, c: Context) => c.text('onError', 500)257258    const composed = compose<Context>(middleware, onError, onNotFound)259    const context = await composed(c)260    expect(context.res).not.toBeNull()261    expect(context.res.status).toBe(500)262    expect(await context.res.text()).toBe('onError')263    expect(context.finalized).toBe(true)264  })265266  it('Error on handler - async', async () => {267    const handler = () => {268      throw new Error()269    }270271    middleware.push(buildMiddlewareTuple(handler))272    const onError = async (_error: Error, c: Context) => c.text('onError', 500)273274    const composed = compose<Context>(middleware, onError)275    const context = await composed(c)276    expect(context.res).not.toBeNull()277    expect(context.res.status).toBe(500)278    expect(await context.res.text()).toBe('onError')279    expect(context.finalized).toBe(true)280  })281282  it('Run all the middlewares', async () => {283    const ctx: C = { req: {}, res: {}, finalized: false }284    const stack: number[] = []285    const middlewares = [286      async (_ctx: C, next: Function) => {287        stack.push(0)288        await next()289      },290      async (_ctx: C, next: Function) => {291        stack.push(1)292        await next()293      },294      async (_ctx: C, next: Function) => {295        stack.push(2)296        await next()297      },298    ].map((h) => buildMiddlewareTuple(h))299    const composed = compose(middlewares)300    await composed(ctx)301    expect(stack).toEqual([0, 1, 2])302  })303})304describe('compose with Context - not finalized', () => {305  const req = new Request('http://localhost/')306  const c: Context = new Context(req)307  const onNotFound = (c: Context) => {308    return c.text('onNotFound', 404)309  }310311  it('Should not be finalized - lack `next()`', async () => {312    const middleware: MiddlewareTuple[] = []313    const mHandler = async (_c: Context, next: Function) => {314      await next()315    }316    const mHandler2 = async () => {}317318    middleware.push(buildMiddlewareTuple(mHandler))319    middleware.push(buildMiddlewareTuple(mHandler2))320    const composed = compose<Context>(middleware, undefined, onNotFound)321    const context = await composed(c)322    expect(context.finalized).toBe(false)323  })324325  it('Should not be finalized - lack `return Response`', async () => {326    const middleware2: MiddlewareTuple[] = []327    const mHandler3 = async (_c: Context, next: Function) => {328      await next()329    }330    const handler = async () => {}331    middleware2.push(buildMiddlewareTuple(mHandler3))332    middleware2.push(buildMiddlewareTuple(handler))333334    const composed = compose<Context>(middleware2, undefined, onNotFound)335    const context = await composed(c)336    expect(context.finalized).toBe(false)337  })338})339340describe('Compose', function () {341  it('should get executed order one by one', async () => {342    const arr: number[] = []343    const stack = []344    const called: boolean[] = []345346    stack.push(347      buildMiddlewareTuple(async (_context: C, next: Function) => {348        called.push(true)349350        arr.push(1)351        await next()352        arr.push(6)353      })354    )355356    stack.push(357      buildMiddlewareTuple(async (_context: C, next: Function) => {358        called.push(true)359360        arr.push(2)361        await next()362        arr.push(5)363      })364    )365366    stack.push(367      buildMiddlewareTuple(async (_context: C, next: Function) => {368        called.push(true)369370        arr.push(3)371        await next()372        arr.push(4)373      })374    )375376    await compose(stack)({ res: null, finalized: false })377    expect(called).toEqual([true, true, true])378    expect(arr).toEqual([1, 2, 3, 4, 5, 6])379  })380381  it('should not get executed if previous next() not triggered', async () => {382    const arr: number[] = []383    const stack = []384    const called: boolean[] = []385386    stack.push(387      buildMiddlewareTuple(async (_context: C, next: Function) => {388        called.push(true)389390        arr.push(1)391        await next()392        arr.push(6)393      })394    )395396    stack.push(397      buildMiddlewareTuple(async () => {398        called.push(true)399        arr.push(2)400      })401    )402403    stack.push(404      buildMiddlewareTuple(async (_context: C, next: Function) => {405        called.push(true)406407        arr.push(3)408        await next()409        arr.push(4)410      })411    )412413    await compose(stack)({ res: null, finalized: false })414    expect(called).toEqual([true, true])415    expect(arr).toEqual([1, 2, 6])416  })417418  it('should be able to be called twice', async () => {419    type C = {420      arr: number[]421    }422    const stack = []423424    stack.push(425      buildMiddlewareTuple(async (context: C, next: Function) => {426        context.arr.push(1)427        await next()428        context.arr.push(6)429      })430    )431432    stack.push(433      buildMiddlewareTuple(async (context: C, next: Function) => {434        context.arr.push(2)435        await next()436        context.arr.push(5)437      })438    )439440    stack.push(441      buildMiddlewareTuple(async (context: C, next: Function) => {442        context.arr.push(3)443        await next()444        context.arr.push(4)445      })446    )447448    const fn = compose(stack)449    const ctx1 = { arr: [] as number[], res: null, finalized: false }450    const ctx2 = { arr: [] as number[], res: null, finalized: false }451    const out = [1, 2, 3, 4, 5, 6]452453    await fn(ctx1)454455    expect(out).toEqual(ctx1.arr)456    await fn(ctx2)457458    expect(out).toEqual(ctx2.arr)459  })460461  it('should create next functions that return a Promise', async () => {462    const stack = []463    const arr: unknown[] = []464    for (let i = 0; i < 5; i++) {465      stack.push(466        buildMiddlewareTuple((_context: C, next: Function) => {467          arr.push(next())468        })469      )470    }471472    await compose(stack)({ res: null, finalized: false })473474    for (const next of arr) {475      const isPromise = !!(next as { then?: Function })?.then476      expect(isPromise).toBe(true)477    }478  })479480  it('should work with 0 middleware', async () => {481    await compose([])({ res: null, finalized: false })482  })483484  it('should work when yielding at the end of the stack', async () => {485    const stack = []486    let called = false487488    stack.push(489      buildMiddlewareTuple(async (_ctx: C, next: Function) => {490        await next()491        called = true492      })493    )494495    await compose(stack)({ res: null, finalized: false })496    expect(called).toBe(true)497  })498499  it('should reject on errors in middleware', async () => {500    const stack = []501502    stack.push(503      buildMiddlewareTuple(() => {504        throw new ExpectedError()505      })506    )507508    try {509      await compose(stack)({ res: null, finalized: false })510      throw new Error('promise was not rejected')511    } catch (e) {512      expect(e).toBeInstanceOf(ExpectedError)513    }514  })515516  it('should keep the context', async () => {517    const ctx = { res: null, finalized: false }518519    const stack = []520521    stack.push(522      buildMiddlewareTuple(async (ctx2: C, next: Function) => {523        await next()524        expect(ctx2).toEqual(ctx)525      })526    )527528    stack.push(529      buildMiddlewareTuple(async (ctx2: C, next: Function) => {530        await next()531        expect(ctx2).toEqual(ctx)532      })533    )534535    stack.push(536      buildMiddlewareTuple(async (ctx2: C, next: Function) => {537        await next()538        expect(ctx2).toEqual(ctx)539      })540    )541542    await compose(stack)(ctx)543  })544545  it('should catch downstream errors', async () => {546    const arr: number[] = []547    const stack = []548549    stack.push(550      buildMiddlewareTuple(async (_ctx: C, next: Function) => {551        arr.push(1)552        try {553          arr.push(6)554          await next()555          arr.push(7)556        } catch {557          arr.push(2)558        }559        arr.push(3)560      })561    )562563    stack.push(564      buildMiddlewareTuple(async () => {565        arr.push(4)566        throw new Error()567      })568    )569570    await compose(stack)({ res: null, finalized: false })571    expect(arr).toEqual([1, 6, 4, 2, 3])572  })573574  it('should compose w/ next', async () => {575    let called = false576577    await compose([])({ res: null, finalized: false }, async () => {578      called = true579    })580    expect(called).toBe(true)581  })582583  it('should handle errors in wrapped non-async functions', async () => {584    const stack = []585586    stack.push(587      buildMiddlewareTuple(function () {588        throw new ExpectedError()589      })590    )591592    try {593      await compose(stack)({ res: null, finalized: false })594      throw new Error('promise was not rejected')595    } catch (e) {596      expect(e).toBeInstanceOf(ExpectedError)597    }598  })599600  // https://github.com/koajs/compose/pull/27#issuecomment-143109739601  it('should compose w/ other compositions', async () => {602    const called: number[] = []603604    await compose([605      buildMiddlewareTuple(606        compose([607          buildMiddlewareTuple((_ctx: C, next: Function) => {608            called.push(1)609            return next()610          }),611          buildMiddlewareTuple((_ctx: C, next: Function) => {612            called.push(2)613            return next()614          }),615        ])616      ),617      buildMiddlewareTuple((_ctx: C, next: Function) => {618        called.push(3)619        return next()620      }),621    ])({ res: null, finalized: false })622623    expect(called).toEqual([1, 2, 3])624  })625626  it('should throw if next() is called multiple times', async () => {627    try {628      await compose([629        buildMiddlewareTuple(async (_ctx: C, next: Function) => {630          await next()631          await next()632        }),633      ])({ res: null, finalized: false })634      throw new Error('boom')635    } catch (err) {636      expect(err instanceof Error && /multiple times/.test(err.message)).toBe(true)637    }638  })639640  it('should return a valid middleware', async () => {641    let val = 0642    await compose([643      buildMiddlewareTuple(644        compose([645          buildMiddlewareTuple((_ctx: C, next: Function) => {646            val++647            return next()648          }),649          buildMiddlewareTuple((_ctx: C, next: Function) => {650            val++651            return next()652          }),653        ])654      ),655      buildMiddlewareTuple((_ctx: C, next: Function) => {656        val++657        return next()658      }),659    ])({ res: null, finalized: false })660661    expect(val).toEqual(3)662  })663664  it('should return last return value', async () => {665    type C = {666      val: number667      finalized: boolean668      res: unknown669    }670    const stack = []671672    stack.push(673      buildMiddlewareTuple(async (ctx: C, next: Function) => {674        await next()675        expect(ctx.val).toEqual(2)676        ctx.val = 1677      })678    )679680    stack.push(681      buildMiddlewareTuple(async (ctx: C, next: Function) => {682        ctx.val = 2683        await next()684        expect(ctx.val).toEqual(2)685      })686    )687688    const res = await compose<C>(stack)({ val: 0, res: null, finalized: false })689    expect(res.val).toEqual(1)690  })691692  it('should not affect the original middleware array', () => {693    const middleware: MiddlewareTuple[] = []694    const fn1 = (_ctx: C, next: Function) => {695      return next()696    }697    middleware.push(buildMiddlewareTuple(fn1))698699    for (const [[fn]] of middleware) {700      expect(fn).toEqual(fn1)701    }702703    compose(middleware)704705    for (const [[fn]] of middleware) {706      expect(fn).toEqual(fn1)707    }708  })709710  it('should not get stuck on the passed in next', async () => {711    type C = {712      middleware: number713      next: number714      finalized: boolean715      res: unknown716    }717718    const middleware = [719      buildMiddlewareTuple((ctx: C, next: Function) => {720        ctx.middleware++721        return next()722      }),723    ]724    const ctx = {725      middleware: 0,726      next: 0,727      finalized: false,728      res: null,729    }730731    await compose<C>(middleware)(ctx, (ctx: C, next: Function) => {732      ctx.next++733      return next()734    })735736    expect(ctx.middleware).toEqual(1)737    expect(ctx.next).toEqual(1)738  })739})