feat(compose): compose both the ordinary middlewares and response (#195)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
middlewares
authored by Minghe · committed by GitHub · parent 785bdc8 · Browse files · 2 files·+348 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+348 added−5 removed
- tests:+343 added−0 removed
- other:+5 added−5 removed
Provenance
- Commit
9810f69- Tree
d3aabab- Author
Minghe <h.minghe@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
785bdc8
2 files changed+348 added−5 removed
modified:src/compose.test.ts+343 added
99 unmodified lines100 expect(c.res).not.toBeNull()101 expect(c.res.status).toBe(500)102 expect(await context.res.text()).toBe('onError')103 })104+105+ it('Run all the middlewares', async () => {106+ const ctx: C = { req: {}, res: {} }107+ const stack: number[] = []108+ const middlewares = [109+ async (ctx: C, next: Function) => {110+ stack.push(0)111+ await next()112+ },113+ async (ctx: C, next: Function) => {114+ stack.push(1)115+ await next()116+ },117+ async (ctx: C, next: Function) => {118+ stack.push(2)119+ await next()120+ },121+ ]122+ const composed = await compose(middlewares)123+ await composed(ctx)124+ expect(stack).toEqual([0, 1, 2])125+ })126 })127+128+describe('Compose', function () {129+ function isPromise(x: any) {130+ return x && typeof x.then === 'function'131+ }132+133+ it('should work', async () => {134+ const arr: number[] = []135+ const stack = []136+137+ stack.push(async (context: C, next: Function) => {138+ arr.push(1)139+ await next()140+ arr.push(6)141+ })142+143+ stack.push(async (context: C, next: Function) => {144+ arr.push(2)145+ await next()146+ arr.push(5)147+ })148+149+ stack.push(async (context: C, next: Function) => {150+ arr.push(3)151+ await next()152+ arr.push(4)153+ })154+155+ await compose(stack)({})156+ expect(arr).toEqual(expect.arrayContaining([1, 2, 3, 4, 5, 6]))157+ })158+159+ it('should be able to be called twice', () => {160+ type C = {161+ arr: number[]162+ }163+ const stack = []164+165+ stack.push(async (context: C, next: Function) => {166+ context.arr.push(1)167+ await next()168+ context.arr.push(6)169+ })170+171+ stack.push(async (context: C, next: Function) => {172+ context.arr.push(2)173+ await next()174+ context.arr.push(5)175+ })176+177+ stack.push(async (context: C, next: Function) => {178+ context.arr.push(3)179+ await next()180+ context.arr.push(4)181+ })182+183+ const fn = compose(stack)184+ const ctx1 = { arr: [] as number[] }185+ const ctx2 = { arr: [] as number[] }186+ const out = [1, 2, 3, 4, 5, 6]187+188+ return fn(ctx1)189+ .then(() => {190+ expect(out).toEqual(ctx1.arr)191+ return fn(ctx2)192+ })193+ .then(() => {194+ expect(out).toEqual(ctx2.arr)195+ })196+ })197+198+ it('should create next functions that return a Promise', function () {199+ const stack: any[] = []200+ const arr: any[] = []201+ for (let i = 0; i < 5; i++) {202+ stack.push((context: C, next: Function) => {203+ arr.push(next())204+ })205+ }206+207+ compose(stack)({})208+209+ for (const next of arr) {210+ expect(isPromise(next)).toBe(true)211+ }212+ })213+214+ it('should work with 0 middleware', function () {215+ return compose([])({})216+ })217+218+ it('should work when yielding at the end of the stack', async () => {219+ const stack = []220+ let called = false221+222+ stack.push(async (ctx: C, next: Function) => {223+ await next()224+ called = true225+ })226+227+ await compose(stack)({})228+ expect(called).toBe(true)229+ })230+231+ it('should reject on errors in middleware', () => {232+ const stack = []233+234+ stack.push(() => {235+ throw new Error()236+ })237+238+ return compose(stack)({}).then(239+ () => {240+ throw new Error('promise was not rejected')241+ },242+ (e) => {243+ expect(e).toBeInstanceOf(Error)244+ }245+ )246+ })247+248+ it('should keep the context', () => {249+ const ctx = {}250+251+ const stack = []252+253+ stack.push(async (ctx2: C, next: Function) => {254+ await next()255+ expect(ctx2).toEqual(ctx)256+ })257+258+ stack.push(async (ctx2: C, next: Function) => {259+ await next()260+ expect(ctx2).toEqual(ctx)261+ })262+263+ stack.push(async (ctx2: C, next: Function) => {264+ await next()265+ expect(ctx2).toEqual(ctx)266+ })267+268+ return compose(stack)(ctx)269+ })270+271+ it('should catch downstream errors', async () => {272+ const arr: any[] = []273+ const stack = []274+275+ stack.push(async (ctx: C, next: Function) => {276+ arr.push(1)277+ try {278+ arr.push(6)279+ await next()280+ arr.push(7)281+ } catch (err) {282+ arr.push(2)283+ }284+ arr.push(3)285+ })286+287+ stack.push(async (ctx: C, next: Function) => {288+ arr.push(4)289+ throw new Error()290+ })291+292+ await compose(stack)({})293+ expect(arr).toEqual([1, 6, 4, 2, 3])294+ })295+296+ it('should compose w/ next', () => {297+ let called = false298+299+ return compose([])({}, async () => {300+ called = true301+ }).then(function () {302+ expect(called).toBe(true)303+ })304+ })305+306+ it('should handle errors in wrapped non-async functions', () => {307+ const stack = []308+309+ stack.push(function () {310+ throw new Error()311+ })312+313+ return compose(stack)({}).then(314+ () => {315+ throw new Error('promise was not rejected')316+ },317+ (e) => {318+ expect(e).toBeInstanceOf(Error)319+ }320+ )321+ })322+323+ // https://github.com/koajs/compose/pull/27#issuecomment-143109739324+ it('should compose w/ other compositions', () => {325+ const called: number[] = []326+327+ return compose([328+ compose([329+ (ctx: C, next: Function) => {330+ called.push(1)331+ return next()332+ },333+ (ctx: C, next: Function) => {334+ called.push(2)335+ return next()336+ },337+ ]),338+ (ctx: C, next: Function) => {339+ called.push(3)340+ return next()341+ },342+ ])({}).then(() => expect(called).toEqual([1, 2, 3]))343+ })344+345+ it('should throw if next() is called multiple times', () => {346+ return compose([347+ async (ctx: C, next: Function) => {348+ await next()349+ await next()350+ },351+ ])({}).then(352+ () => {353+ throw new Error('boom')354+ },355+ (err) => {356+ expect(/multiple times/.test(err.message)).toBe(true)357+ }358+ )359+ })360+361+ it('should return a valid middleware', () => {362+ let val = 0363+ return compose([364+ compose([365+ (ctx: C, next: Function) => {366+ val++367+ return next()368+ },369+ (ctx: C, next: Function) => {370+ val++371+ return next()372+ },373+ ]),374+ (ctx: C, next: Function) => {375+ val++376+ return next()377+ },378+ ])({}).then(function () {379+ expect(val).toEqual(3)380+ })381+ })382+383+ it('should return last return value', async () => {384+ type C = {385+ val: number386+ }387+ const stack = []388+389+ stack.push(async (ctx: C, next: Function) => {390+ await next()391+ expect(ctx.val).toEqual(2)392+ ctx.val = 1393+ })394+395+ stack.push(async (ctx: C, next: Function) => {396+ ctx.val = 2397+ await next()398+ expect(ctx.val).toEqual(2)399+ })400+401+ const res = await compose(stack)({ val: 0 })402+ expect(res).toEqual({ val: 1 })403+ })404+405+ it('should not affect the original middleware array', () => {406+ const middleware = []407+ const fn1 = (ctx: C, next: Function) => {408+ return next()409+ }410+ middleware.push(fn1)411+412+ for (const fn of middleware) {413+ expect(fn).toEqual(fn1)414+ }415+416+ compose(middleware)417+418+ for (const fn of middleware) {419+ expect(fn).toEqual(fn1)420+ }421+ })422+423+ it('should not get stuck on the passed in next', () => {424+ type C = {425+ middleware: number426+ next: number427+ }428+429+ const middleware = [430+ (ctx: C, next: Function) => {431+ ctx.middleware++432+ return next()433+ },434+ ]435+ const ctx = {436+ middleware: 0,437+ next: 0,438+ }439+440+ return compose(middleware)(ctx, (ctx: C, next: Function) => {441+ ctx.next++442+ return next()443+ }).then(() => {444+ expect(ctx).toEqual({ middleware: 1, next: 1 })445+ })446+ })447+})modified:src/compose.ts+5 added-5 removed
12345667891011121011121613141516171819202111 unmodified linesimport { Context } from '@/context'import type { ErrorHandler } from '@/hono'
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C>(middleware: Function[], onError?: ErrorHandler) => { return function (context: C) { return function (context: C, next?: Function) { let index = -1 return dispatch(0) async function dispatch(i: number): Promise<C> { if (i === middleware.length) { return context } if (i <= index) { return Promise.reject(new Error('next() called multiple times')) } const handler = middleware[i] let handler = middleware[i] index = i if (i === middleware.length) handler = next if (!handler) return Promise.resolve(context)
return Promise.resolve(handler(context, dispatch.bind(null, i + 1))) .then(() => { return context })11 unmodified lines