Skip to content
Myr

compose.test.ts

This file

Path

src/compose.test.ts

751 lines 路 19.9 KiB 路 TypeScript

Last changed by

Not known.

History of this file

Take it

1import { compose } from './compose'2import { Context } from './context'3import type { Params } from './router'4import type { Next } from './types'56type MiddlewareTuple = [[Function, unknown], Params]78class ExpectedError extends Error {}910function buildMiddlewareTuple(fn: Function, params?: Params): MiddlewareTuple {11  return [[fn, undefined], params || {}]12}1314describe('compose', () => {15  const middleware: MiddlewareTuple[] = []1617  const a = async (c: Context, next: Next) => {18    c.set('log', 'log')19    await next()20  }2122  const b = async (c: Context, next: Next) => {23    await next()24    c.header('x-custom-header', 'custom-header')25  }2627  const c = async (c: Context, next: Next) => {28    c.set('xxx', 'yyy')29    await next()30    c.set('zzz', 'xxx')31  }3233  const handler = async (c: Context, next: Next) => {34    c.set('log', `${c.get('log')} message`)35    await next()36    return c.json({ message: 'new response' })37  }3839  middleware.push(buildMiddlewareTuple(a))40  middleware.push(buildMiddlewareTuple(b))41  middleware.push(buildMiddlewareTuple(c))42  middleware.push(buildMiddlewareTuple(handler))4344  it('Request', async () => {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 () => {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})6061describe('compose with returning a promise, non-async function', () => {62  const handlers: MiddlewareTuple[] = [63    buildMiddlewareTuple(() => {64      return new Promise((resolve) =>65        setTimeout(() => {66          resolve(67            new Response(JSON.stringify({ message: 'new response' }), {68              headers: {69                'Content-Type': 'application/json',70              },71            })72          )73        })74      )75    }),76  ]7778  it('Response', async () => {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})8485describe('Handler and middlewares', () => {86  const middleware: MiddlewareTuple[] = []8788  const req = new Request('http://localhost/')89  const c: Context = new Context(req)9091  const mHandlerFoo = async (c: Context, next: Next) => {92    c.req.raw.headers.append('x-header-foo', 'foo')93    await next()94  }9596  const mHandlerBar = async (c: Context, next: Next) => {97    await next()98    c.header('x-header-bar', 'bar')99  }100101  const handler = (c: Context) => {102    const foo = c.req.header('x-header-foo') || ''103    return c.text(foo)104  }105106  middleware.push(buildMiddlewareTuple(mHandlerFoo))107  middleware.push(buildMiddlewareTuple(mHandlerBar))108  middleware.push(buildMiddlewareTuple(handler))109110  it('Should return 200 Response', async () => {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)116    expect(await res.text()).toBe('foo')117    expect(res.headers.get('x-header-bar')).toBe('bar')118  })119})120121describe('compose with Context - 200 success', () => {122  const middleware: MiddlewareTuple[] = []123124  const req = new Request('http://localhost/')125  const c: Context = new Context(req)126  const handler = (c: Context) => {127    return c.text('Hello')128  }129  const mHandler = async (_c: Context, next: Next) => {130    await next()131  }132133  middleware.push(buildMiddlewareTuple(handler))134  middleware.push(buildMiddlewareTuple(mHandler))135136  it('Should return 200 Response', async () => {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')142  })143})144145describe('compose with Context - 404 not found', () => {146  const middleware: MiddlewareTuple[] = []147148  const req = new Request('http://localhost/')149  const onNotFound = (c: Context) => {150    return c.text('onNotFound', 404)151  }152  const onNotFoundAsync = async (c: Context) => {153    return c.text('onNotFoundAsync', 404)154  }155  const mHandler = async (_c: Context, next: Next) => {156    await next()157  }158159  middleware.push(buildMiddlewareTuple(mHandler))160161  it('Should return 404 Response', async () => {162    const c: Context = new Context(req)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')168    expect(context.finalized).toBe(true)169  })170171  it('Should return 404 Response - async handler', async () => {172    const c: Context = new Context(req)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')178    expect(context.finalized).toBe(true)179  })180})181182describe('compose with Context - 401 not authorized', () => {183  const middleware: MiddlewareTuple[] = []184185  const req = new Request('http://localhost/')186  const c: Context = new Context(req)187  const handler = (c: Context) => {188    return c.text('Hello')189  }190  const mHandler = async (c: Context, next: Next) => {191    await next()192    c.res = new Response('Not authorized', { status: 401 })193  }194195  middleware.push(buildMiddlewareTuple(mHandler))196  middleware.push(buildMiddlewareTuple(handler))197198  it('Should return 401 Response', async () => {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')204    expect(context.finalized).toBe(true)205  })206})207208describe('compose with Context - next() below', () => {209  const middleware: MiddlewareTuple[] = []210211  const req = new Request('http://localhost/')212  const c: Context = new Context(req)213  const handler = (c: Context) => {214    const message = c.req.header('x-custom') || 'blank'215    return c.text(message)216  }217  const mHandler = async (c: Context, next: Next) => {218    c.req.raw.headers.append('x-custom', 'foo')219    await next()220  }221222  middleware.push(buildMiddlewareTuple(mHandler))223  middleware.push(buildMiddlewareTuple(handler))224225  it('Should return 200 Response', async () => {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')231    expect(context.finalized).toBe(true)232  })233})234235describe('compose with Context - 500 error', () => {236  const middleware: MiddlewareTuple[] = []237238  const req = new Request('http://localhost/')239  const c: Context = new Context(req)240241  it('Error on handler', async () => {242    const handler = () => {243      throw new Error()244    }245246    const mHandler = async (_c: Context, next: Next) => {247      await next()248    }249250    middleware.push(buildMiddlewareTuple(mHandler))251    middleware.push(buildMiddlewareTuple(handler))252253    const onNotFound = (c: Context) => c.text('NotFound', 404)254    const onError = (_error: Error, c: Context) => c.text('onError', 500)255256    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')261    expect(context.finalized).toBe(true)262  })263264  it('Error on handler - async', async () => {265    const handler = () => {266      throw new Error()267    }268269    middleware.push(buildMiddlewareTuple(handler))270    const onError = async (_error: Error, c: Context) => c.text('onError', 500)271272    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  })279280  it('Run all the middlewares', async () => {281    const stack: number[] = []282    const middlewares = [283      async (_ctx: Context, next: Next) => {284        stack.push(0)285        await next()286      },287      async (_ctx: Context, next: Next) => {288        stack.push(1)289        await next()290      },291      async (_ctx: Context, next: Next) => {292        stack.push(2)293        await next()294      },295    ].map((h) => buildMiddlewareTuple(h))296    const composed = compose(middlewares)297    await composed(new Context(new Request('http://localhost/')))298    expect(stack).toEqual([0, 1, 2])299  })300})301describe('compose with Context - not finalized', () => {302  const req = new Request('http://localhost/')303  const c: Context = new Context(req)304  const onNotFound = (c: Context) => {305    return c.text('onNotFound', 404)306  }307308  it('Should not be finalized - lack `next()`', async () => {309    const middleware: MiddlewareTuple[] = []310    const mHandler = async (_c: Context, next: Next) => {311      await next()312    }313    const mHandler2 = async () => {}314315    middleware.push(buildMiddlewareTuple(mHandler))316    middleware.push(buildMiddlewareTuple(mHandler2))317    const composed = compose(middleware, undefined, onNotFound)318    const context = await composed(c)319    expect(context.finalized).toBe(false)320  })321322  it('Should not be finalized - lack `return Response`', async () => {323    const middleware2: MiddlewareTuple[] = []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))330331    const composed = compose(middleware2, undefined, onNotFound)332    const context = await composed(c)333    expect(context.finalized).toBe(false)334  })335})336describe('compose with Context - next', () => {337  const req = new Request('http://localhost/')338  const c: Context = new Context(req)339340  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    }349350    middleware.push(buildMiddlewareTuple(mHandler))351    middleware.push(buildMiddlewareTuple(mHandler2))352353    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})361362describe('Compose', function () {363  it('should get executed order one by one', async () => {364    const arr: number[] = []365    const stack = []366    const called: boolean[] = []367368    stack.push(369      buildMiddlewareTuple(async (_context: Context, next: Next) => {370        called.push(true)371372        arr.push(1)373        await next()374        arr.push(6)375      })376    )377378    stack.push(379      buildMiddlewareTuple(async (_context: Context, next: Next) => {380        called.push(true)381382        arr.push(2)383        await next()384        arr.push(5)385      })386    )387388    stack.push(389      buildMiddlewareTuple(async (_context: Context, next: Next) => {390        called.push(true)391392        arr.push(3)393        await next()394        arr.push(4)395      })396    )397398    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  })402403  it('should not get executed if previous next() not triggered', async () => {404    const arr: number[] = []405    const stack = []406    const called: boolean[] = []407408    stack.push(409      buildMiddlewareTuple(async (_context: Context, next: Next) => {410        called.push(true)411412        arr.push(1)413        await next()414        arr.push(6)415      })416    )417418    stack.push(419      buildMiddlewareTuple(async () => {420        called.push(true)421        arr.push(2)422      })423    )424425    stack.push(426      buildMiddlewareTuple(async (_context: Context, next: Next) => {427        called.push(true)428429        arr.push(3)430        await next()431        arr.push(4)432      })433    )434435    await compose(stack)(new Context(new Request('http://localhost/')))436    expect(called).toEqual([true, true])437    expect(arr).toEqual([1, 2, 6])438  })439440  it('should be able to be called twice', async () => {441    const stack = []442443    stack.push(444      buildMiddlewareTuple(async (context: Context, next: Next) => {445        context.get('arr').push(1)446        await next()447        context.get('arr').push(6)448      })449    )450451    stack.push(452      buildMiddlewareTuple(async (context: Context, next: Next) => {453        context.get('arr').push(2)454        await next()455        context.get('arr').push(5)456      })457    )458459    stack.push(460      buildMiddlewareTuple(async (context: Context, next: Next) => {461        context.get('arr').push(3)462        await next()463        context.get('arr').push(4)464      })465    )466467    const fn = compose(stack)468    const ctx1 = new Context(new Request('http://localhost/'))469470    ctx1.set('arr', [])471472    const ctx2 = new Context(new Request('http://localhost/'))473474    ctx2.set('arr', [])475476    const out = [1, 2, 3, 4, 5, 6]477478    await fn(ctx1)479480    expect(out).toEqual(ctx1.get('arr'))481    await fn(ctx2)482483    expect(out).toEqual(ctx2.get('arr'))484  })485486  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(491        buildMiddlewareTuple((_context: Context, next: Next) => {492          arr.push(next())493        })494      )495    }496497    await compose(stack)(new Context(new Request('http://localhost/')))498499    for (const next of arr) {500      const isPromise = !!(next as { then?: Function })?.then501      expect(isPromise).toBe(true)502    }503  })504505  it('should work with 0 middleware', async () => {506    await compose([])(new Context(new Request('http://localhost/')))507  })508509  it('should work when yielding at the end of the stack', async () => {510    const stack = []511    let called = false512513    stack.push(514      buildMiddlewareTuple(async (_ctx: Context, next: Next) => {515        await next()516        called = true517      })518    )519520    await compose(stack)(new Context(new Request('http://localhost/')))521    expect(called).toBe(true)522  })523524  it('should reject on errors in middleware', async () => {525    const stack = []526527    stack.push(528      buildMiddlewareTuple(() => {529        throw new ExpectedError()530      })531    )532533    try {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  })540541  it('should keep the context', async () => {542    const ctx = new Context(new Request('http://localhost/'))543544    const stack = []545546    stack.push(547      buildMiddlewareTuple(async (ctx2: Context, next: Next) => {548        await next()549        expect(ctx2).toEqual(ctx)550      })551    )552553    stack.push(554      buildMiddlewareTuple(async (ctx2: Context, next: Next) => {555        await next()556        expect(ctx2).toEqual(ctx)557      })558    )559560    stack.push(561      buildMiddlewareTuple(async (ctx2: Context, next: Next) => {562        await next()563        expect(ctx2).toEqual(ctx)564      })565    )566567    await compose(stack)(ctx)568  })569570  it('should catch downstream errors', async () => {571    const arr: number[] = []572    const stack = []573574    stack.push(575      buildMiddlewareTuple(async (_ctx: Context, next: Next) => {576        arr.push(1)577        try {578          arr.push(6)579          await next()580          arr.push(7)581        } catch {582          arr.push(2)583        }584        arr.push(3)585      })586    )587588    stack.push(589      buildMiddlewareTuple(async () => {590        arr.push(4)591        throw new Error()592      })593    )594595    await compose(stack)(new Context(new Request('http://localhost/')))596    expect(arr).toEqual([1, 6, 4, 2, 3])597  })598599  it('should compose w/ next', async () => {600    let called = false601602    await compose([])(new Context(new Request('http://localhost/')), async () => {603      called = true604    })605    expect(called).toBe(true)606  })607608  it('should handle errors in wrapped non-async functions', async () => {609    const stack = []610611    stack.push(612      buildMiddlewareTuple(function () {613        throw new ExpectedError()614      })615    )616617    try {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    }623  })624625  // https://github.com/koajs/compose/pull/27#issuecomment-143109739626  it('should compose w/ other compositions', async () => {627    const called: number[] = []628629    await compose([630      buildMiddlewareTuple(631        compose([632          buildMiddlewareTuple((_ctx: Context, next: Next) => {633            called.push(1)634            return next()635          }),636          buildMiddlewareTuple((_ctx: Context, next: Next) => {637            called.push(2)638            return next()639          }),640        ])641      ),642      buildMiddlewareTuple((_ctx: Context, next: Next) => {643        called.push(3)644        return next()645      }),646    ])(new Context(new Request('http://localhost/')))647648    expect(called).toEqual([1, 2, 3])649  })650651  it('should throw if next() is called multiple times', async () => {652    try {653      await compose([654        buildMiddlewareTuple(async (_ctx: Context, next: Next) => {655          await next()656          await next()657        }),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    }663  })664665  it('should return a valid middleware', async () => {666    let val = 0667    await compose([668      buildMiddlewareTuple(669        compose([670          buildMiddlewareTuple((_ctx: Context, next: Next) => {671            val++672            return next()673          }),674          buildMiddlewareTuple((_ctx: Context, next: Next) => {675            val++676            return next()677          }),678        ])679      ),680      buildMiddlewareTuple((_ctx: Context, next: Next) => {681        val++682        return next()683      }),684    ])(new Context(new Request('http://localhost/')))685686    expect(val).toEqual(3)687  })688689  it('should return last return value', async () => {690    const stack = []691692    stack.push(693      buildMiddlewareTuple(async (ctx: Context, next: Next) => {694        await next()695        expect(ctx.get('val')).toEqual(2)696        ctx.set('val', 1)697      })698    )699700    stack.push(701      buildMiddlewareTuple(async (ctx: Context, next: Next) => {702        ctx.set('val', 2)703        await next()704        expect(ctx.get('val')).toEqual(2)705      })706    )707708    const res = await compose(stack)(new Context(new Request('http://localhost/')))709    expect(res.get('val')).toEqual(1)710  })711712  it('should not affect the original middleware array', () => {713    const middleware: MiddlewareTuple[] = []714    const fn1 = (_ctx: Context, next: Next) => {715      return next()716    }717    middleware.push(buildMiddlewareTuple(fn1))718719    for (const [[fn]] of middleware) {720      expect(fn).toEqual(fn1)721    }722723    compose(middleware)724725    for (const [[fn]] of middleware) {726      expect(fn).toEqual(fn1)727    }728  })729730  it('should not get stuck on the passed in next', async () => {731    const middleware = [732      buildMiddlewareTuple((ctx: Context, next: Next) => {733        ctx.set('middleware', ctx.get('middleware') + 1)734        return next()735      }),736    ]737738    const ctx = new Context(new Request('http://localhost/'))739740    ctx.set('middleware', 0)741    ctx.set('next', 0)742743    await compose(middleware)(ctx, ((ctx: Context, next: Next) => {744      ctx.set('next', ctx.get('next') + 1)745      return next()746    }) as Next)747748    expect(ctx.get('middleware')).toEqual(1)749    expect(ctx.get('next')).toEqual(1)750  })751})